animations

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Phaser 4 -- Sprite Animations

Phaser 4 -- 精灵动画

AnimationManager (global), AnimationState (per-sprite), creating animations from spritesheets and atlases, playing/pausing/chaining, animation events, frame callbacks.
Related skills: ../sprites-and-images/SKILL.md, ../loading-assets/SKILL.md

AnimationManager(全局)、AnimationState(单精灵)、基于精灵表和图集创建动画、播放/暂停/链式动画、动画事件、帧回调。
相关技能: ../sprites-and-images/SKILL.md, ../loading-assets/SKILL.md

Quick Start

快速开始

js
// In preload -- load a spritesheet
this.load.spritesheet('explosion', 'explosion.png', {
    frameWidth: 64,
    frameHeight: 64
});

// In create -- define a global animation
this.anims.create({
    key: 'explode',
    frames: this.anims.generateFrameNumbers('explosion', { start: 0, end: 11 }),
    frameRate: 24,
    repeat: 0
});

// Play it on a sprite
const sprite = this.add.sprite(400, 300, 'explosion');
sprite.play('explode');

js
// 在preload中加载精灵表
this.load.spritesheet('explosion', 'explosion.png', {
    frameWidth: 64,
    frameHeight: 64
});

// 在create中定义全局动画
this.anims.create({
    key: 'explode',
    frames: this.anims.generateFrameNumbers('explosion', { start: 0, end: 11 }),
    frameRate: 24,
    repeat: 0
});

// 在精灵上播放动画
const sprite = this.add.sprite(400, 300, 'explosion');
sprite.play('explode');

Core Concepts

核心概念

AnimationManager vs AnimationState

AnimationManager 与 AnimationState

Phaser has two distinct animation objects:
AspectAnimationManagerAnimationState
Access
this.anims
(in a Scene) or
this.game.anims
sprite.anims
ScopeGlobal -- shared across all scenesPer-sprite instance
PurposeCreate/store animation definitionsControl playback on one Game Object
Class
Phaser.Animations.AnimationManager
Phaser.Animations.AnimationState
The AnimationManager is a singleton owned by the Game. Animations registered there are available in every Scene. The AnimationState lives on each Sprite and handles playback for that specific object.
An
Animation
is a sequence of
AnimationFrame
objects plus timing data. Created via
this.anims.create(config)
(global) or
sprite.anims.create(config)
(local to one sprite).
Phaser包含两个截然不同的动画对象:
方面AnimationManagerAnimationState
访问方式
this.anims
(在场景中)或
this.game.anims
sprite.anims
作用域全局——在所有场景间共享单个精灵实例专属
用途创建/存储动画定义控制单个游戏对象的动画播放
Phaser.Animations.AnimationManager
Phaser.Animations.AnimationState
AnimationManager是游戏拥有的单例对象,在其中注册的动画可在所有场景中使用。AnimationState存在于每个精灵中,负责该特定对象的动画播放控制。
Animation
是由一系列
AnimationFrame
对象加上时间数据组成的序列。可通过
this.anims.create(config)
(全局)或
sprite.anims.create(config)
(仅单个精灵可用)创建。

Local vs Global Animations

本地动画 vs 全局动画

When
sprite.anims.play(key)
is called, it first checks for a local animation with that key, then falls back to the global AnimationManager. Use local for sprite-specific animations; use global when shared across sprites.
js
// Global animation -- available to all sprites
this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });

// Local animation -- only on this sprite
sprite.anims.create({ key: 'walk', frames: 'npc_walk', frameRate: 10, repeat: -1 });

// This plays the LOCAL version because local takes priority
sprite.play('walk');

调用
sprite.anims.play(key)
时,会先检查该精灵是否有同名的本地动画,若没有则回退到全局AnimationManager。精灵专属动画使用本地模式;多个精灵共享的动画使用全局模式。
js
// 全局动画——所有精灵均可使用
this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });

// 本地动画——仅当前精灵可用
sprite.anims.create({ key: 'walk', frames: 'npc_walk', frameRate: 10, repeat: -1 });

// 此处会播放本地版本,因为本地动画优先级更高
sprite.play('walk');

Common Patterns

常见模式

Spritesheet Animation

精灵表动画

Use
generateFrameNumbers
for spritesheets (numeric frame indices).
js
this.load.spritesheet('dude', 'dude.png', { frameWidth: 32, frameHeight: 48 });

// All frames
this.anims.create({
    key: 'run',
    frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 7 }),
    frameRate: 10,
    repeat: -1
});

// Custom frame sequence
this.anims.create({
    key: 'idle',
    frames: this.anims.generateFrameNumbers('dude', { frames: [0, 1, 2, 1] }),
    frameRate: 6,
    repeat: -1
});
generateFrameNumbers
config:
  • start
    (default
    0
    ) -- first frame index
  • end
    (default
    -1
    , meaning last frame) -- final frame index
  • first
    -- a single frame to prepend before the range
  • frames
    -- explicit array of frame indices (overrides start/end)
使用
generateFrameNumbers
处理精灵表(基于数字帧索引)。
js
this.load.spritesheet('dude', 'dude.png', { frameWidth: 32, frameHeight: 48 });

// 使用所有帧
this.anims.create({
    key: 'run',
    frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 7 }),
    frameRate: 10,
    repeat: -1
});

// 自定义帧序列
this.anims.create({
    key: 'idle',
    frames: this.anims.generateFrameNumbers('dude', { frames: [0, 1, 2, 1] }),
    frameRate: 6,
    repeat: -1
});
generateFrameNumbers
配置项:
  • start
    (默认值
    0
    )——起始帧索引
  • end
    (默认值
    -1
    ,表示最后一帧)——结束帧索引
  • first
    ——在帧范围前添加的单个帧
  • frames
    ——明确指定的帧索引数组(会覆盖start/end)

Atlas Animation

图集动画

Use
generateFrameNames
for texture atlases (string-based frame names).
js
this.load.atlas('gems', 'gems.png', 'gems.json');

this.anims.create({
    key: 'ruby_sparkle',
    frames: this.anims.generateFrameNames('gems', {
        prefix: 'ruby_',
        start: 1,
        end: 6,
        zeroPad: 4   // produces ruby_0001 through ruby_0006
    }),
    frameRate: 12,
    repeat: -1
});
generateFrameNames
config:
  • prefix
    -- prepended to each frame number
  • suffix
    -- appended after each frame number
  • start
    ,
    end
    -- numeric range
  • zeroPad
    -- left-pad numbers to this length with zeros
  • frames
    -- explicit array of frame numbers (overrides start/end)
If you call
generateFrameNames(key)
with no config, it returns all frames from the atlas.
使用
generateFrameNames
处理纹理图集(基于字符串帧名称)。
js
this.load.atlas('gems', 'gems.png', 'gems.json');

this.anims.create({
    key: 'ruby_sparkle',
    frames: this.anims.generateFrameNames('gems', {
        prefix: 'ruby_',
        start: 1,
        end: 6,
        zeroPad: 4   // 生成ruby_0001至ruby_0006
    }),
    frameRate: 12,
    repeat: -1
});
generateFrameNames
配置项:
  • prefix
    ——添加到每个帧编号前的前缀
  • suffix
    ——添加到每个帧编号后的后缀
  • start
    ,
    end
    ——数字范围
  • zeroPad
    ——用零将数字填充至指定长度
  • frames
    ——明确指定的帧编号数组(会覆盖start/end)
若调用
generateFrameNames(key)
时不传入配置项,会返回该图集的所有帧。

String as Frames

字符串作为帧参数

Pass a texture key string as
frames
to use all frames from that texture, sorted numerically by default. Set
sortFrames: false
to disable sorting.
js
this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });
传入纹理键字符串作为
frames
参数,会使用该纹理的所有帧,默认按数字排序。设置
sortFrames: false
可禁用排序。
js
this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });

Yoyo and Repeat

往返播放与重复

js
this.anims.create({
    key: 'pulse',
    frames: this.anims.generateFrameNumbers('orb', { start: 0, end: 5 }),
    frameRate: 10,
    yoyo: true,       // plays forward then backward
    repeat: -1,       // -1 = forever
    repeatDelay: 500   // ms pause between each repeat cycle
});
When
yoyo
is true, the animation plays forward then reverses. The full cycle counts as one play.
js
this.anims.create({
    key: 'pulse',
    frames: this.anims.generateFrameNumbers('orb', { start: 0, end: 5 }),
    frameRate: 10,
    yoyo: true,       // 正向播放后反向播放
    repeat: -1,       // -1 = 无限重复
    repeatDelay: 500   // 每次重复循环间的暂停时间(毫秒)
});
yoyo
设为true时,动画先正向播放再反向播放,整个循环算作一次播放。

Chaining Animations

链式动画

js
sprite.play('attack');
sprite.chain('idle');                        // play idle after attack completes
sprite.chain(['fall', 'land', 'idle']);       // chain multiple
sprite.anims.chain();                        // clear the chain queue
Chaining is per-sprite. Chained animations start after
animationcomplete
or
animationstop
. An animation with
repeat: -1
never completes -- call
stop()
to trigger the chain.
js
sprite.play('attack');
sprite.chain('idle');                        // 攻击动画完成后播放 idle
sprite.chain(['fall', 'land', 'idle']);       // 链式播放多个动画
sprite.anims.chain();                        // 清空链式队列
链式动画是单精灵专属的。链式动画会在
animationcomplete
animationstop
事件触发后开始播放。设置
repeat: -1
的动画永远不会完成,需调用
stop()
来触发链式动画。

Playing in Reverse

反向播放

js
// Play an animation from last frame to first
sprite.playReverse('walk');

// Reverse direction mid-playback
sprite.anims.reverse();
playReverse
sets
forward = false
and
inReverse = true
. The
reverse()
method toggles direction mid-playback.
js
// 从最后一帧播放到第一帧
sprite.playReverse('walk');

// 在播放过程中反转方向
sprite.anims.reverse();
playReverse
会设置
forward = false
inReverse = true
reverse()
方法可在播放过程中切换方向。

Play Variants

播放变体

js
sprite.play('walk', true);                   // ignoreIfPlaying = true
sprite.anims.playAfterDelay('walk', 1000);   // play after 1s delay
sprite.anims.playAfterRepeat('walk', 2);     // play after current anim repeats 2x
js
sprite.play('walk', true);                   // ignoreIfPlaying = true(若已播放则忽略)
sprite.anims.playAfterDelay('walk', 1000);   // 延迟1秒后播放
sprite.anims.playAfterRepeat('walk', 2);     // 当前动画重复2次后播放

Animation Mixing

动画过渡混合

Adds a transition delay between two specific animations, set globally on the AnimationManager.
js
this.anims.addMix('idle', 'walk', 200);
this.anims.addMix('walk', 'idle', 300);

sprite.play('idle');
sprite.play('walk');   // 200ms mix delay applied automatically

this.anims.removeMix('idle', 'walk');   // remove specific pair
this.anims.removeMix('idle');           // remove all mixes for 'idle'
Mix delays only apply with
sprite.play()
, not
playAfterDelay
or
playAfterRepeat
.
在AnimationManager上全局设置两个特定动画之间的过渡延迟。
js
this.anims.addMix('idle', 'walk', 200);
this.anims.addMix('walk', 'idle', 300);

sprite.play('idle');
sprite.play('walk');   // 自动应用200毫秒的过渡延迟

this.anims.removeMix('idle', 'walk');   // 删除特定的过渡对
this.anims.removeMix('idle');           // 删除所有与'idle'相关的过渡
过渡延迟仅在调用
sprite.play()
时生效,
playAfterDelay
playAfterRepeat
不会应用过渡延迟。

Pause, Resume, and Stop

暂停、恢复与停止

js
sprite.anims.pause();                 // pause per-sprite
sprite.anims.resume();                // resume per-sprite
this.anims.pauseAll();                // global pause
this.anims.resumeAll();               // global resume

sprite.anims.stop();                  // stop immediately
sprite.anims.stopAfterDelay(2000);    // stop after 2 seconds
sprite.anims.stopAfterRepeat(1);      // stop after 1 more repeat
sprite.anims.stopOnFrame(frame);      // stop when a specific frame is reached
All stop methods fire
animationstop
(not
animationcomplete
). Chained animations trigger after stop.
js
sprite.anims.pause();                 // 暂停单个精灵的动画
sprite.anims.resume();                // 恢复单个精灵的动画
this.anims.pauseAll();                // 全局暂停所有动画
this.anims.resumeAll();               // 全局恢复所有动画

sprite.anims.stop();                  // 立即停止
sprite.anims.stopAfterDelay(2000);    // 2秒后停止
sprite.anims.stopAfterRepeat(1);      // 再重复1次后停止
sprite.anims.stopOnFrame(frame);      // 播放到指定帧时停止
所有停止方法都会触发
animationstop
事件(而非
animationcomplete
)。链式动画会在停止后触发。

Animation Events

动画事件

js
sprite.on('animationcomplete', (anim, frame, gameObject, frameKey) => {
    console.log('completed:', anim.key);
});

// Key-specific complete -- only fires for the named animation
sprite.on('animationcomplete-explode', (anim, frame, gameObject, frameKey) => {
    gameObject.destroy();
});
Available events:
animationstart
,
animationcomplete
,
animationcomplete-{key}
,
animationupdate
,
animationstop
,
animationrepeat
,
animationrestart
. All share the same callback signature:
(animation, frame, gameObject, frameKey)
.
js
sprite.on('animationcomplete', (anim, frame, gameObject, frameKey) => {
    console.log('动画完成:', anim.key);
});

// 指定动画的完成事件——仅当指定动画完成时触发
sprite.on('animationcomplete-explode', (anim, frame, gameObject, frameKey) => {
    gameObject.destroy();
});
可用事件:
animationstart
animationcomplete
animationcomplete-{key}
animationupdate
animationstop
animationrepeat
animationrestart
。所有事件的回调签名均为:
(animation, frame, gameObject, frameKey)

Frame-Level Callbacks via animationupdate

通过animationupdate实现帧级回调

js
sprite.on('animationupdate', (anim, frame, gameObject, frameKey) => {
    if (anim.key === 'attack' && frame.index === 4) {
        this.checkHit(gameObject);
    }
});
js
sprite.on('animationupdate', (anim, frame, gameObject, frameKey) => {
    if (anim.key === 'attack' && frame.index === 4) {
        this.checkHit(gameObject);
    }
});

Per-Frame Duration

单帧时长

Individual frames can have a
duration
(ms) that is added to the base msPerFrame.
js
this.anims.create({
    key: 'combo',
    frames: [
        { key: 'fighter', frame: 'punch1', duration: 50 },
        { key: 'fighter', frame: 'kick', duration: 200 },   // hold longer
        { key: 'fighter', frame: 'recover', duration: 100 }
    ],
    frameRate: 24
});
单个帧可设置
duration
(毫秒),该时长会添加到基础帧时长中。
js
this.anims.create({
    key: 'combo',
    frames: [
        { key: 'fighter', frame: 'punch1', duration: 50 },
        { key: 'fighter', frame: 'kick', duration: 200 },   // 停留更长时间
        { key: 'fighter', frame: 'recover', duration: 100 }
    ],
    frameRate: 24
});

Visibility, Random Start, and TimeScale

可见性、随机起始帧与时间缩放

js
// Visibility control
this.anims.create({
    key: 'appear', frames: 'sparkle', frameRate: 12,
    showOnStart: true,      // sprite.visible = true when anim starts (after delay)
    hideOnComplete: true,   // sprite.visible = false when anim completes
    showBeforeDelay: true   // show first frame immediately even during delay
});

// Random start frame -- each sprite begins on a different frame
this.anims.create({
    key: 'ambient', frames: 'fire', frameRate: 10, repeat: -1,
    randomFrame: true
});

// TimeScale -- per-sprite or global speed control
sprite.anims.timeScale = 2;                         // 2x speed
sprite.play({ key: 'walk', timeScale: 0.5 });       // half speed via config
this.anims.globalTimeScale = 0.5;                    // affects ALL animations
js
// 可见性控制
this.anims.create({
    key: 'appear', frames: 'sparkle', frameRate: 12,
    showOnStart: true,      // 动画开始时(延迟后)设置sprite.visible = true
    hideOnComplete: true,   // 动画完成时设置sprite.visible = false
    showBeforeDelay: true   // 即使在延迟期间也立即显示第一帧
});

// 随机起始帧——每个精灵从不同的帧开始播放
this.anims.create({
    key: 'ambient', frames: 'fire', frameRate: 10, repeat: -1,
    randomFrame: true
});

// 时间缩放——单个精灵或全局速度控制
sprite.anims.timeScale = 2;                         // 2倍速度
sprite.play({ key: 'walk', timeScale: 0.5 });       // 通过配置设置0.5倍速度
this.anims.globalTimeScale = 0.5;                    // 影响所有动画

Staggered Playback

交错播放

js
const enemies = this.add.group({ key: 'enemy', repeat: 9 });
this.anims.staggerPlay('walk', enemies.getChildren(), 100);
// Each sprite starts 100ms after the previous. Pass staggerFirst: false to skip delay on first.
js
const enemies = this.add.group({ key: 'enemy', repeat: 9 });
this.anims.staggerPlay('walk', enemies.getChildren(), 100);
// 每个精灵在前一个精灵启动100毫秒后开始播放。传入staggerFirst: false可取消第一个精灵的延迟。

JSON Export and Import

JSON导出与导入

js
// Export all global animations to JSON
const data = this.anims.toJSON();

// Import animations from JSON (pass true to clear existing animations first)
this.anims.fromJSON(data);
this.anims.fromJSON(data, true);

// Check before creating to avoid duplicate warning
if (!this.anims.exists('walk')) {
    this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });
}
js
// 将所有全局动画导出为JSON
const data = this.anims.toJSON();

// 从JSON导入动画(传入true可先清空现有动画)
this.anims.fromJSON(data);
this.anims.fromJSON(data, true);

// 创建前检查以避免重复警告
if (!this.anims.exists('walk')) {
    this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });
}

Modifying Animation Frames at Runtime

运行时修改动画帧

js
const anim = this.anims.get('walk');

// Add frames to the end
anim.addFrame(this.anims.generateFrameNumbers('player', { start: 8, end: 10 }));

// Insert frames at a specific index
anim.addFrameAt(this.anims.generateFrameNumbers('player', { frames: [5] }), 2);

// Remove a specific frame object
const frame = anim.frames[3];
anim.removeFrame(frame);

// Remove frame at index
anim.removeFrameAt(0);
js
const anim = this.anims.get('walk');

// 在末尾添加帧
anim.addFrame(this.anims.generateFrameNumbers('player', { start: 8, end: 10 }));

// 在指定索引处插入帧
anim.addFrameAt(this.anims.generateFrameNumbers('player', { frames: [5] }), 2);

// 删除特定帧对象
const frame = anim.frames[3];
anim.removeFrame(frame);

// 删除指定索引处的帧
anim.removeFrameAt(0);

Aseprite Support

Aseprite支持

js
this.load.aseprite('paladin', 'paladin.png', 'paladin.json');
// In create:
this.anims.createFromAseprite('paladin');               // all tags
this.anims.createFromAseprite('paladin', ['walk']);      // specific tags only
sprite.play('walk');                                     // play by tag name

js
this.load.aseprite('paladin', 'paladin.png', 'paladin.json');
// 在create中:
this.anims.createFromAseprite('paladin');               // 创建所有标签对应的动画
this.anims.createFromAseprite('paladin', ['walk']);      // 仅创建指定标签的动画
sprite.play('walk');                                     // 通过标签名称播放

Configuration Reference

配置参考

AnimationConfig (used with
this.anims.create()
)

AnimationConfig(用于
this.anims.create()

PropertyTypeDefaultDescription
key
string--Unique identifier for the animation
frames
string or AnimationFrame[]
[]
Texture key string (uses all frames) or array of frame config objects
sortFrames
boolean
true
Numerically sort frames when using a string key
defaultTextureKey
string
null
Fallback texture key if not set per-frame
frameRate
number
24
Playback rate in frames per second (used if
duration
is null)
duration
number
null
Total animation length in ms (derives frameRate if set)
skipMissedFrames
boolean
true
Skip frames when lagging behind
delay
number
0
Delay before playback starts (ms)
repeat
number
0
Times to repeat after first play (-1 = infinite)
repeatDelay
number
0
Delay before each repeat (ms)
yoyo
boolean
false
Reverse back to start before repeating
showBeforeDelay
boolean
false
Show first frame immediately during delay period
showOnStart
boolean
false
Set visible=true when animation starts
hideOnComplete
boolean
false
Set visible=false when animation completes
randomFrame
boolean
false
Start from a random frame
属性类型默认值描述
key
string--动画的唯一标识符
frames
string 或 AnimationFrame[]
[]
纹理键字符串(使用所有帧)或帧配置对象数组
sortFrames
boolean
true
使用字符串键时按数字排序帧
defaultTextureKey
string
null
若未为单帧设置纹理键,则使用此 fallback 纹理键
frameRate
number
24
播放帧率(每秒帧数,当
duration
为null时使用)
duration
number
null
动画总时长(毫秒,若设置则推导frameRate)
skipMissedFrames
boolean
true
当动画滞后时跳过帧
delay
number
0
播放开始前的延迟(毫秒)
repeat
number
0
首次播放后重复的次数(-1 = 无限重复)
repeatDelay
number
0
每次重复前的延迟(毫秒)
yoyo
boolean
false
重复前反向播放至起始帧
showBeforeDelay
boolean
false
在延迟期间立即显示第一帧
showOnStart
boolean
false
动画开始时设置visible=true
hideOnComplete
boolean
false
动画完成时设置visible=false
randomFrame
boolean
false
从随机帧开始播放

PlayAnimationConfig (used with
sprite.play()
)

PlayAnimationConfig(用于
sprite.play()

All AnimationConfig timing properties are available, plus:
PropertyTypeDefaultDescription
key
string or Animation--Animation key or instance to play
startFrame
number
0
Frame index to begin playback from
timeScale
number
1
Speed multiplier for this playback
Values in PlayAnimationConfig override the animation definition for this specific playback instance.
包含所有AnimationConfig的时间属性,额外增加:
属性类型默认值描述
key
string 或 Animation--要播放的动画键或实例
startFrame
number
0
播放的起始帧索引
timeScale
number
1
本次播放的速度乘数
PlayAnimationConfig中的值会覆盖动画定义中的对应值,仅对本次播放生效。

Duration vs FrameRate Priority

Duration与FrameRate优先级

  • If both
    duration
    and
    frameRate
    are null: defaults to 24 fps.
  • If only
    duration
    is set: frameRate is calculated as
    totalFrames / (duration / 1000)
    .
  • If
    frameRate
    is set (even if duration is also set): frameRate wins, and duration is derived as
    (totalFrames / frameRate) * 1000
    .

  • duration
    frameRate
    均为null:默认使用24 fps。
  • 仅设置
    duration
    :frameRate会通过
    totalFrames / (duration / 1000)
    计算得出。
  • 设置了
    frameRate
    (即使同时设置了duration):frameRate优先级更高,duration会通过
    (totalFrames / frameRate) * 1000
    推导得出。

Events

事件

Sprite Event Flow

精灵事件流

  1. animationstart
    -- after delay expires, before first update
  2. animationupdate
    -- each frame change
  3. animationrepeat
    -- each repeat cycle
  4. animationcomplete
    -- natural end (finite repeat)
  5. animationcomplete-{key}
    -- same, with animation key appended
Stopped manually:
animationstop
fires instead of complete. Restarted mid-play:
animationrestart
fires.
All callbacks:
(animation, frame, gameObject, frameKey)
.
  1. animationstart
    ——延迟结束后,首次更新前触发
  2. animationupdate
    ——每帧变化时触发
  3. animationrepeat
    ——每次重复循环时触发
  4. animationcomplete
    ——自然结束(有限重复)时触发
  5. animationcomplete-{key}
    ——同上,但仅针对指定键的动画
手动停止时:触发
animationstop
而非complete事件。播放中途重启时:触发
animationrestart
事件。
所有回调函数签名:
(animation, frame, gameObject, frameKey)

AnimationManager Events

AnimationManager事件

Fire on
this.anims
:
addanimation
,
removeanimation
,
pauseall
,
resumeall
.

this.anims
上触发:
addanimation
removeanimation
pauseall
resumeall

API Quick Reference

API速查

AnimationManager (
this.anims
)

AnimationManager(
this.anims

MethodDescription
create(config)
Create and register a global animation
remove(key)
Remove a global animation by key
get(key)
Get an Animation instance by key
exists(key)
Check if a key is already registered
generateFrameNumbers(key, config)
Generate frame array from a spritesheet
generateFrameNames(key, config)
Generate frame array from an atlas
play(key, children)
Play an animation on an array of Game Objects
staggerPlay(key, children, stagger)
Staggered play across multiple Game Objects
pauseAll()
/
resumeAll()
Pause/resume all animations globally
addMix(animA, animB, delay)
Set transition delay between two animations
removeMix(animA, animB?)
Remove a mix pairing
getMix(animA, animB)
Get the mix delay between two animations
createFromAseprite(key, tags?, target?)
Create animations from Aseprite JSON
toJSON()
Export all animations as JSON data
fromJSON(data, clear?)
Load animations from JSON data (pass
true
to clear existing first)
方法描述
create(config)
创建并注册全局动画
remove(key)
通过键删除全局动画
get(key)
通过键获取Animation实例
exists(key)
检查键是否已注册
generateFrameNumbers(key, config)
从精灵表生成帧数组
generateFrameNames(key, config)
从图集生成帧数组
play(key, children)
在一组游戏对象上播放动画
staggerPlay(key, children, stagger)
在多个游戏对象上交错播放动画
pauseAll()
/
resumeAll()
全局暂停/恢复所有动画
addMix(animA, animB, delay)
设置两个动画之间的过渡延迟
removeMix(animA, animB?)
删除过渡配对
getMix(animA, animB)
获取两个动画之间的过渡延迟
createFromAseprite(key, tags?, target?)
从Aseprite JSON创建动画
toJSON()
将所有动画导出为JSON数据
fromJSON(data, clear?)
从JSON数据加载动画(传入
true
可先清空现有动画)

AnimationState (
sprite.anims
)

AnimationState(
sprite.anims

MethodDescription
play(key, ignoreIfPlaying?)
Play an animation
playReverse(key, ignoreIfPlaying?)
Play an animation in reverse
playAfterDelay(key, delay)
Play after a delay in ms
playAfterRepeat(key, repeatCount?)
Play after current anim repeats N times
chain(key)
Queue animation(s) to play after current one
stop()
Stop immediately
stopAfterDelay(delay)
Stop after a delay in ms
stopAfterRepeat(repeatCount?)
Stop after N more repeats
stopOnFrame(frame)
Stop when a specific frame is reached
pause(atFrame?)
Pause playback
resume(fromFrame?)
Resume playback
restart(includeDelay?, resetRepeats?)
Restart from beginning
reverse()
Reverse direction mid-playback
getName()
Get the current animation key
getFrameName()
Get the current frame key
getProgress()
Get progress 0-1
setProgress(value)
Set progress 0-1
setRepeat(value)
Change repeat count during playback
getTotalFrames()
Get total frame count
create(config)
Create a local animation on this sprite
exists(key)
Check if a local animation exists
get(key)
Get a local animation by key
Key properties:
isPlaying
,
hasStarted
,
currentAnim
,
currentFrame
,
forward
,
inReverse
,
timeScale
.

方法描述
play(key, ignoreIfPlaying?)
播放动画
playReverse(key, ignoreIfPlaying?)
反向播放动画
playAfterDelay(key, delay)
延迟指定毫秒后播放
playAfterRepeat(key, repeatCount?)
当前动画重复N次后播放
chain(key)
队列化动画,在当前动画结束后播放
stop()
立即停止
stopAfterDelay(delay)
延迟指定毫秒后停止
stopAfterRepeat(repeatCount?)
再重复N次后停止
stopOnFrame(frame)
播放到指定帧时停止
pause(atFrame?)
暂停播放
resume(fromFrame?)
恢复播放
restart(includeDelay?, resetRepeats?)
从开头重启
reverse()
播放过程中反转方向
getName()
获取当前动画的键
getFrameName()
获取当前帧的键
getProgress()
获取播放进度(0-1)
setProgress(value)
设置播放进度(0-1)
setRepeat(value)
播放过程中修改重复次数
getTotalFrames()
获取总帧数
create(config)
在当前精灵上创建本地动画
exists(key)
检查本地动画是否存在
get(key)
通过键获取本地动画
关键属性:
isPlaying
hasStarted
currentAnim
currentFrame
forward
inReverse
timeScale

Gotchas

注意事项

  1. Animations are global by default.
    this.anims.create()
    registers across all Scenes. Do not recreate in every Scene -- it logs a warning and returns the existing one.
  2. repeat: -1
    never fires
    animationcomplete
    .
    Use
    stop()
    to end infinite animations. Listen for
    animationstop
    instead.
  3. frameRate
    beats
    duration
    .
    If both are set, frameRate wins. Set only
    duration
    (leave frameRate null) to control total length.
  4. Per-frame
    duration
    is additive.
    Added on top of base msPerFrame, not a replacement.
  5. play()
    stops the current animation
    (fires
    animationstop
    ). Use
    play(key, true)
    to skip if already playing.
  6. Mix delays only work with
    play()
    .
    playAfterDelay
    /
    playAfterRepeat
    bypass mixes.
  7. Local animations override global. Same key on a sprite's local map takes priority.
  8. Sprite shorthand methods.
    sprite.play()
    ,
    sprite.playReverse()
    ,
    sprite.chain()
    ,
    sprite.stop()
    wrap
    sprite.anims.*
    .
  9. Chained anims fire after stop too. Clear the queue with
    sprite.anims.chain()
    before stopping if unwanted.
  10. generateFrameNumbers
    end=-1 means last frame.
    The
    __BASE
    frame is excluded automatically.

  1. 动画默认是全局的
    this.anims.create()
    会在所有场景中注册动画。不要在每个场景中重复创建——这会触发警告并返回已存在的动画。
  2. repeat: -1
    永远不会触发
    animationcomplete
    。使用
    stop()
    结束无限循环动画,监听
    animationstop
    事件。
  3. frameRate
    优先级高于
    duration
    。若两者都设置,frameRate生效。仅设置
    duration
    (留空frameRate)以控制总时长。
  4. 单帧
    duration
    是累加的
    。是在基础帧时长之上增加,而非替换。
  5. play()
    会停止当前动画
    (触发
    animationstop
    )。使用
    play(key, true)
    可在已播放时忽略调用。
  6. 过渡延迟仅对
    play()
    生效
    playAfterDelay
    /
    playAfterRepeat
    会绕过过渡延迟。
  7. 本地动画覆盖全局动画。精灵本地动画映射中同名的键优先级更高。
  8. 精灵快捷方法
    sprite.play()
    sprite.playReverse()
    sprite.chain()
    sprite.stop()
    sprite.anims.*
    的封装。
  9. 链式动画在停止后也会触发。若不需要,可在停止前调用
    sprite.anims.chain()
    清空队列。
  10. generateFrameNumbers
    的end=-1表示最后一帧
    __BASE
    帧会自动排除。

Source File Map

源文件映射

FilePurpose
src/animations/AnimationManager.js
Global singleton -- create, remove, get, generateFrame*, mix, staggerPlay
src/animations/Animation.js
Animation definition -- frames, timing, yoyo, repeat logic
src/animations/AnimationState.js
Per-sprite component -- play, stop, pause, chain, events
src/animations/AnimationFrame.js
Single frame data -- textureKey, textureFrame, duration, progress
src/animations/events/index.js
All animation event constants
src/animations/typedefs/Animation.js
AnimationConfig typedef
src/animations/typedefs/PlayAnimationConfig.js
PlayAnimationConfig typedef
src/animations/typedefs/GenerateFrameNumbers.js
Config for generateFrameNumbers
src/animations/typedefs/GenerateFrameNames.js
Config for generateFrameNames
文件用途
src/animations/AnimationManager.js
全局单例——创建、删除、获取、generateFrame*、过渡混合、交错播放
src/animations/Animation.js
动画定义——帧、时间、往返播放、重复逻辑
src/animations/AnimationState.js
单精灵组件——播放、停止、暂停、链式动画、事件
src/animations/AnimationFrame.js
单帧数据——纹理键、纹理帧、时长、进度
src/animations/events/index.js
所有动画事件常量
src/animations/typedefs/Animation.js
AnimationConfig类型定义
src/animations/typedefs/PlayAnimationConfig.js
PlayAnimationConfig类型定义
src/animations/typedefs/GenerateFrameNumbers.js
generateFrameNumbers的配置类型定义
src/animations/typedefs/GenerateFrameNames.js
generateFrameNames的配置类型定义