Premium Features
Time to replace that red square with an actual character. In this lesson, we'll extend the Sprite class to handle animated sprite sheets, giving our player life through frame-by-frame animation.
Make Player inherit from Sprite to gain image rendering capabilities:
class Player extends Sprite { constructor({ position, imageSrc, frameRate, animations }) { super({ position, imageSrc, frameRate }) // Player-specific properties... } }By extending Sprite, our Player automatically gets the
draw()method without duplicating code.
A sprite sheet contains multiple frames in a single image. We crop to show one frame at a time:
// In Sprite constructor this.frameRate = frameRate || 1 this.currentFrame = 0 this.frameBuffer = 12 // Frames to wait before switching this.elapsedFrames = 0The canvas drawImage() method can crop a source image:
c.drawImage( this.image, this.currentFrame * (this.image.width / this.frameRate), // Source X 0, // Source Y this.image.width / this.frameRate, // Source Width this.image.height, // Source Height this.position.x, // Dest X this.position.y, // Dest Y this.image.width / this.frameRate, // Dest Width this.image.height // Dest Height )Increment the current frame at a controlled rate:
updateFrames() { this.elapsedFrames++ if (this.elapsedFrames % this.frameBuffer === 0) { if (this.currentFrame < this.frameRate - 1) { this.currentFrame++ } else if (this.loop) { this.currentFrame = 0 } } }Sprite animation transforms a static game into something alive. This same technique works for enemies, effects, and environmental animations.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one