Sprite animations
Frame animations: made once in the global Animation Manager, this.anims, and played on a Sprite through its Animation State, sprite.anims.
Source: src/animations/AnimationManager.js, src/animations/AnimationState.js, src/animations/Animation.js, src/animations/events/, src/animations/typedefs/. Related: loading-assets, sprites-and-images, particles.
Quick start
preload ()
{
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
}
create ()
{
// Global: made once, and playable by any Sprite in any Scene
if (!this.anims.exists('walk'))
{
this.anims.create({
key: 'walk',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 7 }),
frameRate: 10,
repeat: -1
});
}
const player = this.add.sprite(this.scale.width / 2, this.scale.height / 2, 'dude');
player.play('walk');
}
this.animsis the game's one Animation Manager, the same in every Scene. Creating a key which exists logs a warning and returns the existing animation unchanged, so guard withexistsin a Scene that can restart.- Create animations in
create(), after the textures have loaded. A frame that isn't in the texture is skipped with a console warning. sprite.play(key)returns the Sprite. A missing key logsMissing animationand does nothing.- A Sprite animates in its
preUpdate, so it must be in the Scene:this.add.sprite, orscene.add.existing(this)in a custom class.
Frames
| Helper | For | Config and defaults |
|---|---|---|
generateFrameNumbers(key, config) |
Spritesheets: frame indexes | start: 0, end: -1 (the last frame), first, frames: [ ... ] |
generateFrameNames(key, config) |
Atlases: built frame names | prefix: '', start: 0, end: 0, suffix: '', zeroPad: 0, frames: [ ... ] |
// 'ruby_0001' to 'ruby_0006'
this.anims.generateFrameNames('gems', { prefix: 'ruby_', start: 1, end: 6, zeroPad: 4 });
// A custom order
this.anims.generateFrameNumbers('dude', { frames: [ 0, 1, 2, 1 ] });
// start above end gives the frames backwards
this.anims.generateFrameNumbers('dude', { start: 7, end: 0 });
generateFrameNames(key)with no config returns every frame in the atlas, in atlas order. With a config,enddefaults to 0, so set it.frames: 'textureKey'in the animation config uses every frame of that texture, sorted numerically (sortFrames: falsekeeps the texture's order).- Or list the frames:
[ { key: 'fighter', frame: 'punch', duration: 50 }, ... ].defaultTextureKeysaves repeatingkey.
Animation config
For this.anims.create(config). The typedef is src/animations/typedefs/Animation.js.
| Key | Default | Notes |
|---|---|---|
frameRate |
24 | Frames per second. Wins over duration when both are set |
duration |
Length of the whole animation in ms. Only used when frameRate isn't set |
|
delay |
0 |
ms before it starts |
repeat |
0 |
Extra plays. -1 repeats forever |
repeatDelay |
0 |
ms before each repeat |
yoyo |
false |
Plays back to the start before repeating |
showBeforeDelay |
false |
Shows the first frame during the delay |
showOnStart / hideOnComplete |
false |
Sets the Sprite's visible |
randomFrame |
false |
Starts on a random frame |
skipMissedFrames |
true |
Skips frames when it falls behind |
- A frame's own
duration(ms) replaces the frame time for that frame, but only while the animation plays at its own frame rate. AframeRategiven toplaydrops every per-frame duration; change the speed withtimeScaleto keep them. - With neither
frameRatenordurationit plays at 24 fps, but the animation'sdurationproperty is wrong (an engine issue). SetframeRateif you readanim.duration.
Playing and stopping
const sprite = this.add.sprite(this.scale.width / 2, 400, 'dude');
sprite.play('walk'); // restarts 'walk' if it's already playing
sprite.play('walk', true); // ignoreIfPlaying: use this every frame in update()
sprite.playReverse('walk');
sprite.play({ key: 'walk', frameRate: 20, repeat: 2, startFrame: 3, timeScale: 1.5 });
sprite.playAfterDelay('idle', 500);
sprite.playAfterRepeat('idle', 1); // after the current animation repeats once more
sprite.stop(); // fires animationstop, not animationcomplete
sprite.stopAfterDelay(2000);
sprite.stopAfterRepeat(1);
sprite.anims.pause();
sprite.anims.resume();
sprite.anims.restart();
sprite.anims.reverse(); // flips the direction mid-play
sprite.anims.timeScale = 2;
- The values in a play config override the animation's for that play only.
timeScaleis the exception: it stays on the Sprite until you change it. - To change the speed of one play, use
frameRateortimeScale. Adurationin a play config currently has no effect (an engine issue). sprite.animshas the state:isPlaying,currentAnim(null before the first play),currentFrame,getName(),getFrameName(),getProgress()(0 to 1, negative while in reverse),nextFrame(),previousFrame().currentFrame.indexstarts at 1.currentFrame.textureFrameis the frame name or number in the texture.stopOnFrame(frame)takes anAnimationFrame, such assprite.anims.currentAnim.getLastFrame().setFrameon an animating Sprite is replaced at the animation's next frame. Stop it first.
Chains and mixes
const fighter = this.add.sprite(this.scale.width / 2, 400, 'fighter');
fighter.play('attack');
fighter.chain([ 'recover', 'idle' ]); // queued, played in turn
fighter.chain(); // clears the queue
this.anims.addMix('idle', 'walk', 200); // play('walk') during 'idle' waits 200 ms
this.anims.removeMix('idle', 'walk');
- The next chained animation starts when the current one completes or is stopped. A
repeat: -1animation never completes: end it withstop()orstopAfterRepeat(). play()on a playing Sprite firesanimationstopfor the old animation. The chain stays queued, and plays after the new animation. Before 4.3, the next chained animation started and was replaced at once, so it was lost.- Only
play()applies a mix.playAfterDelay,playAfterRepeatand chains don't.
Events
Animation events are emitted by the Game Object playing them. Use Phaser.Animations.Events:
| Constant | String | When |
|---|---|---|
ANIMATION_START |
'animationstart' |
After any delay |
ANIMATION_UPDATE |
'animationupdate' |
Each new frame |
ANIMATION_REPEAT |
'animationrepeat' |
Each repeat |
ANIMATION_COMPLETE |
'animationcomplete' |
It ends by itself. Never for repeat: -1 |
ANIMATION_COMPLETE_KEY + key |
'animationcomplete-explode' |
The same, for one key |
ANIMATION_STOP |
'animationstop' |
stop(), the stopAfter and stopOnFrame methods, or play() over it |
ANIMATION_RESTART |
'animationrestart' |
restart() |
Every listener gets (animation, frame, gameObject, frameKey).
const boom = this.add.sprite(this.scale.width / 2, 300, 'explosion').play('explode');
boom.once(Phaser.Animations.Events.ANIMATION_COMPLETE_KEY + 'explode', () => boom.destroy());
boom.on(Phaser.Animations.Events.ANIMATION_UPDATE, (anim, frame) =>
{
if (frame.index === 4)
{
this.cameras.main.shake(100, 0.01);
}
});
A Game Object's listeners go when it is destroyed. The Animation Manager's own events are ADD_ANIMATION ('add'), REMOVE_ANIMATION ('remove'), PAUSE_ALL and RESUME_ALL, with (key, animation) for the first two. this.anims outlives the Scene, so remove those listeners on shutdown:
const onAdd = (key, anim) => console.log('animation added', key, anim.frames.length);
this.anims.on(Phaser.Animations.Events.ADD_ANIMATION, onAdd);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
this.anims.off(Phaser.Animations.Events.ADD_ANIMATION, onAdd);
});
Manager controls
this.anims.get(key)returnsundefinedwhen there is no such animation.this.anims.remove(key)stops it on every Sprite playing it, then emits'remove'.this.anims.globalTimeScale = 0.5slows every animation.this.anims.pauseAll()andresumeAll()pause global animations on every Sprite. They don't reach local animations, or global ones created afterpauseAll(an engine issue). To pause one animation everywhere:this.anims.get('walk').pause().this.anims.play(key, children)plays on many Game Objects at once.this.anims.staggerPlay(key, children, 100)starts each one 100 ms after the one before:
const enemies = this.add.group({ key: 'enemy', repeat: 9, setXY: { x: 100, y: 300, stepX: 80 } });
this.anims.staggerPlay('walk', enemies.getChildren(), 100);
Local animations
sprite.anims.create(config) makes an animation only that Sprite can play. play(key) looks for a local key first, then a global one. sprite.anims.get, exists, remove, generateFrameNumbers, generateFrameNames and createFromAseprite(key, tags) work the same way.
Aseprite
// preload
this.load.aseprite('paladin', 'assets/paladin.png', 'assets/paladin.json');
// create: one animation per tag, keyed by the tag name
this.anims.createFromAseprite('paladin');
this.anims.createFromAseprite('paladin', [ 'walk', 'War Cry' ]); // only these tags, case-sensitive
this.add.sprite(this.scale.width / 2, 400, 'paladin').play({ key: 'walk', repeat: -1 });
- Export from Aseprite with the "Item Filename" set to
{frame}and "Tags" ticked in the Meta options. Hash or Array JSON both work. The steps are in the JSDoc ofcreateFromAseprite. - Each frame keeps its Aseprite duration. A
reversetag plays backwards, andpingpongsetsyoyo. The tag's repeat count isn't read, so each animation plays once: passrepeattoplay. - Change the speed with
timeScale. AframeRatedrops the Aseprite frame durations. - It returns the animations. If a key already exists, the existing animation is kept, with a warning.
- The third argument, a Game Object, makes them local to it:
this.anims.createFromAseprite('paladin', null, sprite).
Animation JSON
this.load.animation('baddies', 'assets/baddies.json')creates the animations in the file, withfromJSON, after the rest of the load has finished, so it can be loaded with its textures.this.anims.toJSON()andthis.anims.fromJSON(data, clearCurrent). Since 4.3,JSON.stringifyworks on an object or array that holdsthis.anims.
Other Game Objects
TileSpriteandRopehave.animstoo. TileSprite has noplayshortcut:tileSprite.anims.play('flow'). Rope hasrope.play(key).- Particles animate with
animin the emitter config. See particles. SpriteGPULayer.setAnimations(WebGL only) takes Animations, or{ name, duration, frames }objects, and runs them on the GPU, with no events or per-frame durations. Give an Animation passed to it aframeRateorduration.
Gotchas
- Listen for
'add'and'remove'onthis.anims, not'addanimation'or'removeanimation', which are never emitted. delay,repeatDelayand framedurationare in ms.frameRateis per second.- Listening on the Sprite for
ANIMATION_COMPLETEfires for every animation it plays. Checkanim.key, or useANIMATION_COMPLETE_KEY + key. - A Sprite made with
this.make.sprite(config, false)ornew Phaser.GameObjects.Sprite()and never added to the Scene doesn't animate.
