360 Secure SkillHub
360 安全技能中心

animations

面向 Phaser 4 开发者的精灵帧动画参考,覆盖动画管理器的创建与帧生成、播放/停止/链式动画、事件、Aseprite 与 JSON 导入、全局与局部动画,并列出常见 API 误用和注意事项。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-04 05:18:49

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/animations
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
animations
description
Frame animation in Phaser 4: the global Animation Manager (this.anims.create, generateFrameNumbers, generateFrameNames, createFromAseprite, addMix, staggerPlay) and each Sprite's Animation State (sprite.play, playReverse, chain, stop, timeScale), animation events, Aseprite and animation JSON. Use when animating a walk, run, jump or idle cycle, an explosion or a coin from a spritesheet or atlas, switching animations from input, or running code when an animation ends. Corrects old habits: the Animation Manager events are 'add' and 'remove' (not 'addanimation'), animation events fire on the Sprite, frameRate beats duration, play() over a running animation fires animationstop. Triggers on: animation, anims, sprite.play, spritesheet, atlas animation, chain, animationcomplete, frameRate, generateFrameNumbers, Aseprite, walk cycle.
metadata
{"phaser-version":"4.3.0"}

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.anims is 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 with exists in 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 logs Missing animation and does nothing.
  • A Sprite animates in its preUpdate, so it must be in the Scene: this.add.sprite, or scene.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, end defaults to 0, so set it.
  • frames: 'textureKey' in the animation config uses every frame of that texture, sorted numerically (sortFrames: false keeps the texture's order).
  • Or list the frames: [ { key: 'fighter', frame: 'punch', duration: 50 }, ... ]. defaultTextureKey saves repeating key.

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. A frameRate given to play drops every per-frame duration; change the speed with timeScale to keep them.
  • With neither frameRate nor duration it plays at 24 fps, but the animation's duration property is wrong (an engine issue). Set frameRate if you read anim.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. timeScale is the exception: it stays on the Sprite until you change it.
  • To change the speed of one play, use frameRate or timeScale. A duration in a play config currently has no effect (an engine issue).
  • sprite.anims has the state: isPlaying, currentAnim (null before the first play), currentFrame, getName(), getFrameName(), getProgress() (0 to 1, negative while in reverse), nextFrame(), previousFrame().
  • currentFrame.index starts at 1. currentFrame.textureFrame is the frame name or number in the texture.
  • stopOnFrame(frame) takes an AnimationFrame, such as sprite.anims.currentAnim.getLastFrame().
  • setFrame on 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: -1 animation never completes: end it with stop() or stopAfterRepeat().
  • play() on a playing Sprite fires animationstop for 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, playAfterRepeat and 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) returns undefined when there is no such animation.
  • this.anims.remove(key) stops it on every Sprite playing it, then emits 'remove'.
  • this.anims.globalTimeScale = 0.5 slows every animation.
  • this.anims.pauseAll() and resumeAll() pause global animations on every Sprite. They don't reach local animations, or global ones created after pauseAll (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 of createFromAseprite.
  • Each frame keeps its Aseprite duration. A reverse tag plays backwards, and pingpong sets yoyo. The tag's repeat count isn't read, so each animation plays once: pass repeat to play.
  • Change the speed with timeScale. A frameRate drops 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, with fromJSON, after the rest of the load has finished, so it can be loaded with its textures.
  • this.anims.toJSON() and this.anims.fromJSON(data, clearCurrent). Since 4.3, JSON.stringify works on an object or array that holds this.anims.

Other Game Objects

  • TileSprite and Rope have .anims too. TileSprite has no play shortcut: tileSprite.anims.play('flow'). Rope has rope.play(key).
  • Particles animate with anim in 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 a frameRate or duration.

Gotchas

  • Listen for 'add' and 'remove' on this.anims, not 'addanimation' or 'removeanimation', which are never emitted.
  • delay, repeatDelay and frame duration are in ms. frameRate is per second.
  • Listening on the Sprite for ANIMATION_COMPLETE fires for every animation it plays. Check anim.key, or use ANIMATION_COMPLETE_KEY + key.
  • A Sprite made with this.make.sprite(config, false) or new Phaser.GameObjects.Sprite() and never added to the Scene doesn't animate.