Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Sprites and Animation

Phaser Spritesheets and Frame Animation

Animate Phaser sprites: spritesheets and atlases, frames, anims.create, generateFrameNumbers, frame rate, repeat, yoyo, animation events and chaining, with live demos.

A moving cartoon is a flipbook: a stack of slightly different pictures shown one after another. A game character works the same way. Each picture is a frame, the frames are stored together in one image called a spritesheet, and Phaser's animation manager plays them at the speed you choose.

Why one big image?

Instead of loading walk1.png, walk2.png, walk3.png..., artists pack all frames into one image. Loading one file is faster than many small ones, and the graphics card switches textures less often, which makes drawing faster. There are two layouts:

Layout Loader Best for
Spritesheet: a grid of equal-size frames load.spritesheet(key, url, { frameWidth, frameHeight }) simple characters, coins, tiles
Atlas: frames of different sizes, described by a JSON file load.atlas(key, imageUrl, jsonUrl) big games; tools such as TexturePacker or Free Texture Packer create them
JavaScript
preload() {
  // a 4 x 2 grid of 48 x 48 frames in one 192 x 96 image
  this.load.spritesheet('hero', 'assets/hero.png', { frameWidth: 48, frameHeight: 48 });
}

Frames in a spritesheet are numbered from 0, left to right, then top to bottom. Frame 5 of a 4-column sheet is row 1, column 1. You can display a single frame with this.add.sprite(x, y, 'hero', 5).

To keep the examples runnable without image files, the code below draws its own spritesheet into a canvas texture and registers each cell as a numbered frame. After that, everything is the same as with a loaded sheet. The helper is the only part you would replace with load.spritesheet.

Creating animations

An animation is a named recipe: which frames, how fast, how many times. You create it once with the global animation manager (this.anims), and then any sprite can play it by name:

JavaScript
this.anims.create({
  key: 'walk',
  frames: this.anims.generateFrameNumbers('hero', { start: 0, end: 3 }),
  frameRate: 8,        // frames per second
  repeat: -1           // -1 loops forever
});

const hero = this.add.sprite(100, 100, 'hero');
hero.play('walk');

Key options:

  • frames: build with generateFrameNumbers('key', { start, end }) or an explicit list such as { frames: [0, 1, 2, 1] }, or generateFrameNames('atlas', { prefix: 'walk_', start: 1, end: 6, zeroPad: 2 }) for atlas frames named walk_01, walk_02...
  • frameRate (frames per second) or duration (total ms for one cycle);
  • repeat: 0 plays once, -1 forever, n repeats n more times;
  • yoyo: true: play forward, then backward;
  • delay and repeatDelay: waits before the start or between repeats;
  • hideOnComplete: hide the sprite when it ends (explosions).

Animations are global: define them once (in a Boot scene) and use them in every scene. Defining the same key twice gives a warning; guard with if (!this.anims.exists('walk')) in scenes that may restart.

Playing and controlling

JavaScript
sprite.play('walk');                    // start (restarts if already playing)
sprite.play('walk', true);              // ignoreIfPlaying: keep going if it is already 'walk'
sprite.stop();                          // stop on the current frame
sprite.anims.pause(); sprite.anims.resume();
sprite.anims.timeScale = 2;             // twice as fast
sprite.setFrame(0);                     // show a still frame
sprite.anims.isPlaying;                 // boolean
sprite.anims.currentAnim.key;           // which one is playing

The second argument true to play is important in update: calling play('walk') every frame would restart the animation at frame 0 each time, so it would never advance. Use play('walk', true).

A spinning coin and a walking blob

One animation (spin) drives two sprites at different speeds: the animation is a recipe, the sprite holds the playback state.

Animation events

Animations announce what they do. Listen on the sprite (sprite.on(...)) or, for more detail, on sprite.anims:

Event When
animationstart an animation starts
animationupdate the frame changes
animationrepeat a loop begins again
animationcomplete the animation finished (not for infinite loops)
animationcomplete-KEY the specific animation named KEY finished

Events let you sync the game to the artwork: spawn a puff at the exact frame where a foot hits the ground, or remove an explosion sprite when its last frame shows.

JavaScript
const boom = this.add.sprite(x, y, 'explosion').play('boom');
boom.once('animationcomplete', () => boom.destroy());

Chaining and queueing

JavaScript
hero.play('jump').chain('fall').chain('idle');   // play in order
hero.playAfterDelay('walk', 500);                // wait half a second first
hero.playAfterRepeat('idle', 2);                 // after the current animation repeats twice

chain is useful for attack sequences (windup, strike, recover) and for one-shot animations that return to idle by themselves.

Events and chaining

The log shows the order: start boom, complete boom, start idle. The first idle started before the listeners were attached, so it is not reported, and an infinite loop never reports complete.

Animation from a spritesheet with several actions

Real characters share one sheet for idle, walk and jump. Slice it with several generateFrameNumbers ranges:

JavaScript
this.anims.create({ key: 'idle', frames: this.anims.generateFrameNumbers('hero', { start: 0, end: 3 }), frameRate: 4, repeat: -1 });
this.anims.create({ key: 'walk', frames: this.anims.generateFrameNumbers('hero', { start: 4, end: 9 }), frameRate: 10, repeat: -1 });
this.anims.create({ key: 'jump', frames: [{ key: 'hero', frame: 10 }], frameRate: 1 });

Then in update, choose by state: if (moving) hero.play('walk', true); else hero.play('idle', true);. The platformer lesson (Platformer Movement and Jumping) puts it all together.

Common mistakes

  • frameWidth or frameHeight do not divide the image. Frames look cut or shifted. Measure the sheet.
  • Padding or margin in the sheet. Pass margin and spacing in the load config.
  • Calling play every frame without true. The animation restarts and stays on frame 0.
  • Defining an animation twice. Check this.anims.exists(key).
  • Animating at the wrong speed. frameRate is frames per second; 8 to 12 is typical for walk cycles.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a spritesheet?

    A spritesheet packs the frames into one image so a single file and texture can supply an entire animation.
  2. 2. Why use sprite.play('walk', true) inside update()?

    The second argument is ignoreIfPlaying. Without it, calling play each frame restarts the animation.
  3. 3. Which animation setting makes it loop forever?

    repeat -1 repeats without end; yoyo only plays backwards after forwards.
  4. 4. Where should you create animations so every scene can use them?

    The animation manager is shared by the whole game, so define each animation once, for example in a Boot scene.

Summary

  • Pack frames into a spritesheet (grid) or an atlas (JSON-described frames) and load with load.spritesheet or load.atlas.
  • Create animations once with this.anims.create, using generateFrameNumbers or generateFrameNames, frameRate, repeat and yoyo.
  • Start them with sprite.play(key); use play(key, true) in update and chain to queue.
  • Listen to animationstart, animationupdate, animationrepeat and animationcomplete to sync gameplay with animation.
  • Animations are recipes: many sprites can share one at different speeds.

Next: Tweens and Timelines