Premium Features
Let's swap between different sprite sheets based on the player's current action.
Create an animations object containing all sprite sheets with their frame data:
this.animations = { idle: { image: idleImage, frameCount: 8 }, run: { image: runImage, frameCount: 8 }, jump: { image: jumpImage, frameCount: 2 }, fall: { image: fallImage, frameCount: 2 } }Create a method that swaps the current sprite when the player's state changes:
switchSprite(key) { if (this.image === this.animations[key].image) return this.image = this.animations[key].image this.frameCount = this.animations[key].frameCount this.currentFrame = 0 }The early return prevents resetting the animation every frame — we only switch when the sprite actually changes.
Call switchSprite() based on player state:
Moving left/right → switchSprite('run')
Velocity Y < 0 → switchSprite('jump')
Velocity Y > 0 → switchSprite('fall')
Standing still → switchSprite('idle')
Your character now animates based on their actions.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one