assets/2d-platform-game.md · 24000
s.game.physics.arcade.collide(this.hero, this.platforms); this.game.physics.arcade.collide(this.spiders, this.platforms); this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
this.game.physics.arcade.overlap(
this.hero, this.coins, this._onHeroVsCoin, null, this
);
this.game.physics.arcade.overlap(
this.hero, this.spiders, this._onHeroVsEnemy, null, this
);
};
To make spiders reverse direction when colliding with walls, check their velocity each frame and flip them:
```javascript
// In PlayState.update, after collision handling, update spider directions:
PlayState.update = function () {
this._handleCollisions();
this._handleInput();
// Update spider facing direction based on velocity
this.spiders.forEach(function (spider) {
if (spider.body.touching.right || spider.body.blocked.right) {
spider.body.velocity.x = -Spider.SPEED; // Turn left
} else if (spider.body.touching.left || spider.body.blocked.left) {
spider.body.velocity.x = Spider.SPEED; // Turn right
}
}, this);
};
- When a spider touches a wall on its right side, it reverses to move left, and vice versa.
body.touchingis set by Phaser after collision resolution.
Death
Implement hero death when touching enemies and the stomp mechanic for killing enemies.
Hero vs Enemy: Stomp or Die
When the hero overlaps with a spider, check if the hero is falling (stomping) or not:
PlayState._onHeroVsEnemy = function (hero, enemy) {
if (hero.body.velocity.y > 0) {
// Hero is falling -> stomp the enemy
enemy.body.velocity.x = 0; // Stop enemy movement
enemy.body.enable = false; // Disable enemy physics
// Play die animation then remove the enemy
enemy.animations.play('die');
enemy.events.onAnimationComplete.addOnce(function () {
enemy.kill();
});
// Bounce the hero up after stomping
hero.body.velocity.y = -JUMP_SPEED / 2;
this.sfx.stomp.play();
} else {
// Hero touched enemy from side or below -> die
this._killHero();
}
};
PlayState._killHero = function () {
this.hero.kill();
// Restart the level after a short delay
this.game.time.events.add(500, function () {
this.game.state.restart(true, false, { level: this.level });
}, this);
};
- If
hero.body.velocity.y > 0, the hero is moving downward (falling), indicating a stomp. - On stomp: the enemy stops, plays its death animation, and is removed. The hero bounces up.
- If the hero is not falling, the hero dies.
this.hero.kill()removes the hero from the game. - After 500ms, the entire state is restarted, effectively reloading the level.
Add Stomp Sound
// In PlayState.create, add to sfx:
this.sfx = {
jump: this.game.add.audio('sfx:jump'),
coin: this.game.add.audio('sfx:coin'),
stomp: this.game.add.audio('sfx:stomp')
};
Adding a Death Animation for the Hero
Make the hero flash and fall off the screen when dying:
PlayState._killHero = function () {
this.hero.alive = false;
// Play a "dying" visual: the hero jumps up and falls off screen
this.hero.body.velocity.y = -JUMP_SPEED / 2;
this.hero.body.velocity.x = 0;
this.hero.body.allowGravity = true;
// Disable collisions so the hero falls through platforms
this.hero.body.collideWorldBounds = false;
// Restart after a delay
this.game.time.events.add(1000, function () {
this.game.state.restart(true, false, { level: this.level });
}, this);
};
Guarding Input When Dead
Prevent input from controlling the hero after death:
PlayState._handleInput = function () {
if (!this.hero.alive) { return; }
if (this.keys.left.isDown) {
this.hero.body.velocity.x = -SPEED;
} else if (this.keys.right.isDown) {
this.hero.body.velocity.x = SPEED;
} else {
this.hero.body.velocity.x = 0;
}
if (this.keys.up.isDown) {
this._jump();
}
};
this.hero.aliveis set tofalsein_killHero, so input is ignored after death and the hero falls off screen naturally.
Scoreboard
Display the number of collected coins on screen using a bitmap font.
Loading the Bitmap Font
// In PlayState.preload:
this.game.load.image('font:numbers', 'images/numbers.png');
this.game.load.image('icon:coin', 'images/coin_icon.png');
Creating the HUD
Create a fixed HUD (heads-up display) that shows the coin icon and count:
PlayState._createHud = function () {
let coinIcon = this.game.make.image(0, 0, 'icon:coin');
// Create a dynamic text label for the coin count
this.hud = this.game.add.group();
// Use a retroFont or a regular text object for the score
let scoreStyle = {
font: '30px monospace',
fill: '#fff'
};
this.coinFont = this.game.add.text(
coinIcon.width + 7, 0, 'x0', scoreStyle
);
this.hud.add(coinIcon);
this.hud.add(this.coinFont);
this.hud.position.set(10, 10);
this.hud.fixedToCamera = true;
};
Alternatively, using Phaser's RetroFont for pixel-art number rendering:
PlayState._createHud = function () {
// Bitmap-based number rendering using RetroFont
this.coinFont = this.game.add.retroFont(
'font:numbers', 20, 26,
'0123456789X ', 6
);
let coinIcon = this.game.make.image(0, 0, 'icon:coin');
let coinScoreImg = this.game.make.image(
coinIcon.x + coinIcon.width + 7, 0, this.coinFont
);
this.hud = this.game.add.group();
this.hud.add(coinIcon);
this.hud.add(coinScoreImg);
this.hud.position.set(10, 10);
this.hud.fixedToCamera = true;
};
retroFontcreates a bitmap font from a spritesheet containing character glyphs.- Parameters: image key, character width, character height, character set string, number of characters per row.
Calling createHud in create
PlayState.create = function () {
this.game.add.image(0, 0, 'background');
this._loadLevel(this.game.cache.getJSON('level:1'));
// Create the HUD
this._createHud();
};
Updating the Score Display
Update the score text whenever a coin is collected:
PlayState._onHeroVsCoin = function (hero, coin) {
this.sfx.coin.play();
coin.kill();
this.coinPickupCount++;
// Update the HUD
this.coinFont.text = 'x' + this.coinPickupCount;
};
Animations for the Main Character
Replace the static hero image with a spritesheet and add animations for different states: idle (stopped), running, jumping, and falling.
Loading the Hero Spritesheet
Replace the single image load with a spritesheet in preload:
// Replace: this.game.load.image('hero', 'images/hero_stopped.png');
// With:
this.game.load.spritesheet('hero', 'images/hero.png', 36, 42);
- The hero spritesheet is 36 pixels wide and 42 pixels tall per frame.
- Frames include idle, walk cycle, jump, and fall poses.
Defining Animations
In _spawnCharacters, add animation definitions after creating the hero sprite:
PlayState._spawnCharacters = function (data) {
this.hero = this.game.add.sprite(data.hero.x, data.hero.y, 'hero');
this.hero.anchor.set(0.5, 1);
this.game.physics.enable(this.hero);
// Define animations
this.hero.animations.add('stop', [0]); // Single frame: idle
this.hero.animations.add('run', [1, 2], 8, true); // 2 frames at 8fps, looping
this.hero.animations.add('jump', [3]); // Single frame: jumping up
this.hero.animations.add('fall', [4]); // Single frame: falling down
};
animations.add(name, frames, fps, loop)registers an animation with the given name.- Single-frame animations like
stop,jump, andfalleffectively set a static pose. - The
runanimation alternates between frames 1 and 2 at 8fps.
Playing the Correct Animation
Add a method to determine and play the right animation based on the hero's current state:
PlayState._getAnimationName = function () {
let name = 'stop'; // Default: standing still
if (!this.hero.alive) {
name = 'stop'; // Use idle frame when dead
} else if (this.hero.body.velocity.y < 0) {
name = 'jump'; // Moving upward
} else if (this.hero.body.velocity.y > 0 && !this.hero.body.touching.down) {
name = 'fall'; // Moving downward and not on ground
} else if (this.hero.body.velocity.x !== 0 && this.hero.body.touching.down) {
name = 'run'; // Moving horizontally on the ground
}
return name;
};
Flipping the Sprite Based on Direction
Update the hero's facing direction and play the animation in update:
PlayState.update = function () {
this._handleCollisions();
this._handleInput();
// Flip sprite based on movement direction
if (this.hero.body.velocity.x < 0) {
this.hero.scale.x = -1; // Face left
} else if (this.hero.body.velocity.x > 0) {
this.hero.scale.x = 1; // Face right
}
// Play the appropriate animation
this.hero.animations.play(this._getAnimationName());
// Update spider directions
this.spiders.forEach(function (spider) {
if (spider.body.touching.right || spider.body.blocked.right) {
spider.body.velocity.x = -Spider.SPEED;
} else if (spider.body.touching.left || spider.body.blocked.left) {
spider.body.velocity.x = Spider.SPEED;
}
}, this);
};
this.hero.scale.x = -1flips the sprite horizontally to face left. Setting it to1faces right. Because the anchor is at(0.5, 1), the flip looks natural.animations.play()only restarts the animation if the name changes, so calling it every frame is safe and efficient.
Win Condition
Add a door and key mechanic: the hero must collect a key, then reach the door to complete the level.
Loading Door and Key Assets
// In PlayState.preload:
this.game.load.spritesheet('door', 'images/door.png', 42, 66);
this.game.load.spritesheet('key', 'images/key.png', 20, 22); // Key bobbing animation
this.game.load.image('icon:key', 'images/key_icon.png');
this.game.load.audio('sfx:key', 'audio/sfx/key.wav');
this.game.load.audio('sfx:door', 'audio/sfx/door.wav');
Spawning the Door and Key
Update _loadLevel and _spawnCharacters:
PlayState._loadLevel = function (data) {
this.platforms = this.game.add.group();
this.coins = this.game.add.group();
this.spiders = this.game.add.group();
this.enemyWalls = this.game.add.group();
this.bgDecoration = this.game.add.group();
// Must spawn decorations first (background layer)
// Spawn door before hero so it renders behind the hero
data.platforms.forEach(this._spawnPlatform, this);
data.coins.forEach(this._spawnCoin, this);
data.spiders.forEach(this._spawnSpider, this);
this._spawnDoor(data.door.x, data.door.y);
this._spawnKey(data.key.x, data.key.y);
this._spawnCharacters({ hero: data.hero });
this.enemyWalls.visible = false;
this.coinPickupCount = 0;
this.hasKey = false;
};
PlayState._spawnDoor = function (x, y) {
this.door = this.bgDecoration.create(x, y, 'door');
this.door.anchor.setTo(0.5, 1);
this.game.physics.enable(this.door);
this.door.body.allowGravity = false;
};
PlayState._spawnKey = function (x, y) {
this.key = this.bgDecoration.create(x, y, 'key');
this.key.anchor.set(0.5, 0.5);
this.game.physics.enable(this.key);
this.key.body.allowGravity = false;
// Add a bobbing up-and-down tween to the key
this.key.y -= 3;
this.game.add.tween(this.key)
.to({ y: this.key.y + 6 }, 800, Phaser.Easing.Sinusoidal.InOut)
.yoyo(true)
.loop()
.start();
};
- The door is placed in a background decoration group so it renders behind the hero.
- The key has a sinusoidal bobbing tween that moves it 6 pixels up and down over 800ms, looping forever.
Collecting the Key and Opening the Door
Add key and door sound effects to the sfx object:
// In PlayState.create sfx:
this.sfx = {
jump: this.game.add.audio('sfx:jump'),
coin: this.game.add.audio('sfx:coin'),
stomp: this.game.add.audio('sfx:stomp'),
key: this.game.add.audio('sfx:key'),
door: this.game.add.audio('sfx:door')
};
Add overlap detection for the key and door in _handleCollisions:
PlayState._handleCollisions = function () {
this.game.physics.arcade.collide(this.hero, this.platforms);
this.game.physics.arcade.collide(this.spiders, this.platforms);
this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
this.game.physics.arcade.overlap(
this.hero, this.coins, this._onHeroVsCoin, null, this
);
this.game.physics.arcade.overlap(
this.hero, this.spiders, this._onHeroVsEnemy, null, this
);
this.game.physics.arcade.overlap(
this.hero, this.key, this._onHeroVsKey, null, this
);
this.game.physics.arcade.overlap(
this.hero, this.door, this._onHeroVsDoor,
// Only trigger if the hero has the key
function (hero, door) {
return this.hasKey && hero.body.touching.down;
}, this
);
};
- The door overlap has a process callback (the fourth argument) that only triggers the overlap callback when
this.hasKeyis true and the hero is standing on something. This prevents the hero from entering the door while falling or without the key.
Key and Door Callbacks
PlayState._onHeroVsKey = function (hero, key) {
this.sfx.key.play();
key.kill();
this.hasKey = true;
};
PlayState._onHeroVsDoor = function (hero, door) {
this.sfx.door.play();
// Freeze the hero and play the door opening animation
hero.body.velocity.x = 0;
hero.body.velocity.y = 0;
hero.body.enable = false;
// Play door open animation (transition from closed to open frame)
door.frame = 1; // Switch to "open" frame
// Advance to the next level after a short delay
this.game.time.events.add(500, this._goToNextLevel, this);
};
PlayState._goToNextLevel = function () {
this.camera.fade('#000');
this.camera.onFadeComplete.addOnce(function () {
this.game.state.restart(true, false, {
level: this.level + 1
});
}, this);
};
- When the hero touches the key, the key is removed and
hasKeyis set totrue. - When the hero reaches the door (with the key), the hero freezes, the door opens, and after a delay the game transitions to the next level.
camera.fade()creates a fade-to-black transition for a polished level switch.
Showing the Key Icon in the HUD
Update _createHud to show whether the hero has collected the key:
PlayState._createHud = function () {
this.keyIcon = this.game.make.image(0, 19, 'icon:key');
this.keyIcon.anchor.set(0, 0.5);
// ... existing coin HUD code ...
this.hud.add(this.keyIcon);
this.hud.add(coinIcon);
this.hud.add(coinScoreImg);
this.hud.position.set(10, 10);
this.hud.fixedToCamera = true;
};
Update the key icon appearance each frame in update:
// In PlayState.update, add:
this.keyIcon.frame = this.hasKey ? 1 : 0;
- Frame 0 shows a grayed-out key icon; frame 1 shows the collected key icon.
Switching Levels
Support multiple levels by loading different JSON files based on a level index.
Passing Level Number Through init
Modify init to accept a level parameter:
PlayState.init = function (data) {
this.game.renderer.renderSession.roundPixels = true;
this.keys = this.game.input.keyboard.addKeys({
left: Phaser.KeyCode.LEFT,
right: Phaser.KeyCode.RIGHT,
up: Phaser.KeyCode.UP
});
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.gravity.y = 1200;
// Store the current level number (default to 0)
this.level = (data.level || 0) % LEVEL_COUNT;
};
const LEVEL_COUNT = 2; // Total number of levels
datais an object passed fromgame.state.start()orgame.state.restart().- The modulo operation (
% LEVEL_COUNT) wraps around to level 0 after the last level, creating an infinite loop of levels.
Loading Level Data Dynamically
Update preload to load the correct level based on this.level:
PlayState.preload = function () {
this.game.load.image('background', 'images/background.png');
// Load the current level's JSON data
this.game.load.json('level:0', 'data/level00.json');
this.game.load.json('level:1', 'data/level01.json');
// ... load all other assets ...
};
Update create to use the correct level data:
PlayState.create = function () {
this.sfx = {
jump: this.game.add.audio('sfx:jump'),
coin: this.game.add.audio('sfx:coin'),
stomp: this.game.add.audio('sfx:stomp'),
key: this.game.add.audio('sfx:key'),
door: this.game.add.audio('sfx:door')
};
this.game.add.image(0, 0, 'background');
// Load level data based on current level number
this._loadLevel(this.game.cache.getJSON('level:' + this.level));
this._createHud();
};
Starting the Game at Level 0
Update the initial state start to pass level 0:
window.onload = function () {
let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
game.state.add('play', PlayState);
game.state.start('play', true, false, { level: 0 });
};
- The third and fourth
startarguments control world/cache clearing.true, falsekeeps the cache between restarts (so assets do not need to be reloaded) but clears the world. { level: 0 }is passed toinitas thedataparameter.
Level Transition Flow
The complete level flow is:
- Hero collects key ->
hasKey = true - Hero reaches door ->
_onHeroVsDoorfires - Camera fades to black ->
_goToNextLevelfires - State restarts with
{ level: this.level + 1 } initreceives the new level number- The correct level JSON is loaded and the game continues
Moving Forward
Congratulations -- you have built a complete 2D platformer. Here are ideas for extending the game further:
Suggested Improvements
- Mobile / touch controls: Add on-screen buttons or swipe gestures using
game.input.onDownfor touch-enabled devices. - More levels: Create additional JSON level files with new platform layouts, coin placements, and enemy configurations.
- Menu screen: Add a
MenuStatewith a title screen and start button before enteringPlayState. - Game over screen: Instead of instantly restarting, show a "Game Over" screen with the score.
- Lives system: Give the hero multiple lives instead of instant restart.
- Power-ups: Add items like speed boosts, double jump, or invincibility.
- Moving platforms: Create platforms that travel along a path using tweens.
- Different enemy types: Add flying enemies, enemies that shoot projectiles, or enemies with different movement patterns.
- Parallax scrolling: Add multiple background layers that scroll at different speeds for depth.
- Camera scrolling: For levels wider than the screen, use
game.camera.follow(this.hero)to scroll with the hero. - Sound and music: Add background music and additional sound effects for a more polished experience.
- Particle effects: Use Phaser's particle emitter for coin collection sparkles, enemy death effects, or dust when landing.
Full Game Source Reference
Below is the complete main.js file combining all steps for reference. This represents the final state of the game with all features:
// =============================================================================
// Constants
// =============================================================================
const SPEED = 200;
const JUMP_SPEED = 600;
const LEVEL_COUNT = 2;
const Spider = { SPEED: 100 };
// =============================================================================
// Game State: PlayState
// =============================================================================
PlayState = {};
// -----------------------------------------------------------------------------
// init
// -----------------------------------------------------------------------------
PlayState.init = function (data) {
this.game.renderer.renderSession.roundPixels = true;
this.keys = this.game.input.keyboard.addKeys({
left: Phaser.KeyCode.LEFT,
right: Phaser.KeyCode.RIGHT,
up: Phaser.KeyCode.UP
});
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.gravity.y = 1200;
this.level = (data.level || 0) % LEVEL_COUNT;
};
// -----------------------------------------------------------------------------
// preload
// -----------------------------------------------------------------------------
PlayState.preload = function () {
// Background
this.game.load.image('background', 'images/background.png');
// Level data
this.game.load.json('level:0', 'data/level00.json');
this.game.load.json('level:1', 'data/level01.json');
// Platform tiles
this.game.load.image('ground', 'images/ground.png');
this.game.load.image('grass:8x1', 'images/grass_8x1.png');
this.game.load.image('grass:6x1', 'images/grass_6x1.png');
this.game.load.image('grass:4x1', 'images/grass_4x1.png');
this.game.load.image('grass:2x1', 'images/grass_2x1.png');
this.game.load.image('grass:1x1', 'images/grass_1x1.png');
// Characters
this.game.load.spritesheet('hero', 'images/hero.png', 36, 42);
this.game.load.spritesheet('spider', 'images/spider.png', 42, 32);
this.game.load.image('invisible-wall', 'images/invisible_wall.png');
// Collectibles
this.game.load.spritesheet('coin', 'images/coin_animated.png', 22, 22);
this.game.load.spritesheet('key', 'images/key.png', 20, 22);
this.game.load.spritesheet('door', 'images/door.png', 42, 66);
// HUD
this.game.load.image('icon:coin', 'images/coin_icon.png');
this.game.load.image('icon:key', 'images/key_icon.png');
this.game.load.image('font:numbers', 'images/numbers.png');
// Audio
this.game.load.audio('sfx:jump', 'audio/sfx/jump.wav');
this.game.load.audio('sfx:coin', 'audio/sfx/coin.wav');
this.game.load.audio('sfx:stomp', 'audio/sfx/stomp.wav');
this.game.load.audio('sfx:key', 'audio/sfx/key.wav');
this.game.load.audio('sfx:door', 'audio/sfx/door.wav');
};
// -----------------------------------------------------------------------------
// create
// -----------------------------------------------------------------------------
PlayState.create = function () {
// Sound effects
this.sfx = {
jump: this.game.add.audio('sfx:jump'),
coin: this.game.add.audio('sfx:coin'),
stomp: this.game.add.audio('sfx:stomp'),
key: this.game.add.audio('sfx:key'),
door: this.game.add.audio('sfx:door')
};
// Background
this.game.add.image(0, 0, 'background');
// Load level
this._loadLevel(this.game.cache.getJSON('level:' + this.level));
// HUD
this._createHud();
};
// -----------------------------------------------------------------------------
// update
// -----------------------------------------------------------------------------
PlayState.update = function () {
this._handleCollisions();
this._handleInput();
// Update hero sprite direction and animation
if (this.hero.body.velocity.x < 0) {
this.hero.scale.x = -1;
} else if (this.hero.body.velocity.x > 0) {