How to Make a Retro 2D JavaScript Game Part 2


Let’s make this game interactive! We’ll add a player, movement controls, and falling items.
Note: If you'd rather have a video tutorial, here it is:
The full source code is here. Here’s a playable version of the final game.
1. Adding Placeholder Graphics
Update the create
function to add shapes representing the player and falling items:
function create() {
// Player (Blue rectangle)
this.player = this.add.rectangle(400, 550, 50, 50, 0x0000ff);
// Falling item (Green rectangle)
this.item = this.add.rectangle(400, 50, 50, 50, 0x00ff00);
// Enable physics
this.physics.add.existing(this.player);
this.physics.add.existing(this.item);
// Player controls
this.cursors = this.input.keyboard.createCursorKeys();
}
2. Moving the Player Left and Right
Add movement logic to the update
function:
function update() {
// Move player left
if (this.cursors.left.isDown) {
this.player.x -= 5;
}
// Move player right
else if (this.cursors.right.isDown) {
this.player.x += 5;
}
}
- The player can now move left and right using arrow keys!
3. Adding Simple Collision Logic
We need to update our config:
change:
type: Phaser.AUTO, // Auto-detect WebGL or Canvas
width: 800, // Game width
height: 600, // Game height
To this, to add physics and gravity to our scene.
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 }
}
},
Make the falling item reset its position when it reaches the bottom:
function update() {
// Move falling item
this.item.y += 3;
// Reset item position
if (this.item.y > 600) {
this.item.y = 50;
this.item.x = Phaser.Math.Between(50, 750); // Random x-position
}
// Check for overlap
if (Phaser.Geom.Intersects.RectangleToRectangle(this.player.getBounds(), this.item.getBounds())) {
console.log('Caught an item!');
this.item.y = 50;
this.item.x = Phaser.Math.Between(50, 750);
}
}
Now you'll see a screen that looks like this: and you should see green blocks falling. You can also move the player with your arrow keys:
📝 Recap: You added player movement, falling items, and basic collision detection. Your game is interactive! Now on to part 3
Note: If you'd rather have a video tutorial, it’s available here.
Subscribe to my newsletter
Read articles from Jeremy Morgan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Jeremy Morgan
Jeremy Morgan
I'm a coder, blogger, and training architect for Kode Kloud. Follow me for content related to development and cloud.