Premium Features
Sprite swapping
An idle player should look idle. A running player should look like they're running. In this lesson, we'll implement sprite swapping to change animations based on player state.
Defining Animation States
Pass an animations object when creating the player:
const player = new Player({ position: { x: 100, y: 100 }, animations: { idleRight: { imageSrc: './img/king/idle.png', frameRate: 11, frameBuffer: 12 }, runRight: { imageSrc: './img/king/runRight.png', frameRate: 8, frameBuffer: 6 }, runLeft: { imageSrc: './img/king/runLeft.png', frameRate: 8, frameBuffer: 6 } } })Preloading Animation Images
Load all animation images upfront to prevent stuttering:
// In Player constructor for (let key in animations) { const image = new Image() image.src = animations[key].imageSrc animations[key].image = image } this.animations = animationsSwitching Animations
Create a method to swap the current sprite:
switchSprite(name) { if (this.image === this.animations[name].image) return this.image = this.animations[name].image this.frameRate = this.animations[name].frameRate this.frameBuffer = this.animations[name].frameBuffer this.currentFrame = 0 }Triggering Animation Changes
In the animation loop, switch sprites based on velocity:
// In animate() if (player.velocity.x > 0) { player.switchSprite('runRight') } else if (player.velocity.x < 0) { player.switchSprite('runLeft') } else { player.switchSprite('idleRight') }The early return in
switchSpriteprevents resetting the animation every frame when the state hasn't changed.
Why This Matters
Animation states bring personality to your character. Players intuitively understand what's happening based on visual feedback.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one