51: (Bonus Lesson) Animation with Spritesheets

A sprite is a visual element. A spritesheet is a single image file with many visual elements. A quick image search on the web for "spritesheet" will give you a wide variety of examples, many of which are spritesheets for character animations. These spritesheets are often organized in such a way that all the sprites on a single row make up one animation.

For instance, each row of the spritesheet below includes the sprites needed to complete one walk cycle in a particular direction.

Image adapted from: https://gamedev.stackexchange.com/questions/127767/getting-sprites-from-a-spritesheet-with-rows-and-columns

Using a single spritesheet for character animation results in a more polished game than having to switch between different animated GIFs each time the character's animation needs to change. This is because switching between different animated GIF files could result in a flash as the src of an image is replaced by a newly loading image.

Animating with a spritesheet requires only one image, so there is no need to load a new image each time the animation changes. Instead, the entire spritesheet is added as the background-image of an element. The element is set to the size of a single sprite of the spritesheet and its overflow property is set to none so the other sprites on the sheet are not visible. Then, the spritesheet is just continuously shifted horizontally within the element to play an animation; and the spritesheet is shifted vertically to change between animations of the same character.

Here is an example of applying the skeleton spritesheet to set up an animated character controller. View the page source to see the HTML, CSS, and JavaScript.

Finally, create your own spritesheet for a character to use in your platformer game. Implement the spritesheet so that the character appears in the game with a running animation (left and right), a jumping animation (left and right) and an idle animation (for when the player is just standing still).

Example

Save Dr. E uses the spritesheet below, which depicts a run cycle of the character from the game Braid. The characters animation in the game is quite slow and could be sped up dramatically by removing frames from the run cycle. Typically, 8 frames is typically sufficient for a run cycle. A single frame of the spritesheet is shown for the idle, and another frame is shown for the jump. Lastly, the entire spritesheet is flipped horizontally when the player begins to run left.

Feel free to visit burkecs.org/platformer to download the project files and follow the "Activity Instructions" to challenge yourself further. Some of the solutions are provided at burkecs.org/platformer/codingSolutions.pdf.

Have fun coding!