animations
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePhaser 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:
| Aspect | AnimationManager | AnimationState |
|---|---|---|
| Access | | |
| Scope | Global -- shared across all scenes | Per-sprite instance |
| Purpose | Create/store animation definitions | Control playback on one Game Object |
| Class | | |
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 is a sequence of objects plus timing data. Created via (global) or (local to one sprite).
AnimationAnimationFramethis.anims.create(config)sprite.anims.create(config)Phaser包含两个截然不同的动画对象:
| 方面 | AnimationManager | AnimationState |
|---|---|---|
| 访问方式 | | |
| 作用域 | 全局——在所有场景间共享 | 单个精灵实例专属 |
| 用途 | 创建/存储动画定义 | 控制单个游戏对象的动画播放 |
| 类 | | |
AnimationManager是游戏拥有的单例对象,在其中注册的动画可在所有场景中使用。AnimationState存在于每个精灵中,负责该特定对象的动画播放控制。
AnimationAnimationFramethis.anims.create(config)sprite.anims.create(config)Local vs Global Animations
本地动画 vs 全局动画
When 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.
sprite.anims.play(key)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');调用时,会先检查该精灵是否有同名的本地动画,若没有则回退到全局AnimationManager。精灵专属动画使用本地模式;多个精灵共享的动画使用全局模式。
sprite.anims.play(key)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 for spritesheets (numeric frame indices).
generateFrameNumbersjs
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- (default
start) -- first frame index0 - (default
end, meaning last frame) -- final frame index-1 - -- a single frame to prepend before the range
first - -- explicit array of frame indices (overrides start/end)
frames
使用处理精灵表(基于数字帧索引)。
generateFrameNumbersjs
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 - ——明确指定的帧索引数组(会覆盖start/end)
frames
Atlas Animation
图集动画
Use for texture atlases (string-based frame names).
generateFrameNamesjs
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- -- prepended to each frame number
prefix - -- appended after each frame number
suffix - ,
start-- numeric rangeend - -- left-pad numbers to this length with zeros
zeroPad - -- explicit array of frame numbers (overrides start/end)
frames
If you call with no config, it returns all frames from the atlas.
generateFrameNames(key)使用处理纹理图集(基于字符串帧名称)。
generateFrameNamesjs
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 - ——明确指定的帧编号数组(会覆盖start/end)
frames
若调用时不传入配置项,会返回该图集的所有帧。
generateFrameNames(key)String as Frames
字符串作为帧参数
Pass a texture key string as to use all frames from that texture, sorted numerically by default. Set to disable sorting.
framessortFrames: falsejs
this.anims.create({ key: 'walk', frames: 'player_walk', frameRate: 12, repeat: -1 });传入纹理键字符串作为参数,会使用该纹理的所有帧,默认按数字排序。设置可禁用排序。
framessortFrames: falsejs
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 is true, the animation plays forward then reverses. The full cycle counts as one play.
yoyojs
this.anims.create({
key: 'pulse',
frames: this.anims.generateFrameNumbers('orb', { start: 0, end: 5 }),
frameRate: 10,
yoyo: true, // 正向播放后反向播放
repeat: -1, // -1 = 无限重复
repeatDelay: 500 // 每次重复循环间的暂停时间(毫秒)
});当设为true时,动画先正向播放再反向播放,整个循环算作一次播放。
yoyoChaining 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 queueChaining is per-sprite. Chained animations start after or . An animation with never completes -- call to trigger the chain.
animationcompleteanimationstoprepeat: -1stop()js
sprite.play('attack');
sprite.chain('idle'); // 攻击动画完成后播放 idle
sprite.chain(['fall', 'land', 'idle']); // 链式播放多个动画
sprite.anims.chain(); // 清空链式队列链式动画是单精灵专属的。链式动画会在或事件触发后开始播放。设置的动画永远不会完成,需调用来触发链式动画。
animationcompleteanimationstoprepeat: -1stop()Playing in Reverse
反向播放
js
// Play an animation from last frame to first
sprite.playReverse('walk');
// Reverse direction mid-playback
sprite.anims.reverse();playReverseforward = falseinReverse = truereverse()js
// 从最后一帧播放到第一帧
sprite.playReverse('walk');
// 在播放过程中反转方向
sprite.anims.reverse();playReverseforward = falseinReverse = truereverse()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 2xjs
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 , not or .
sprite.play()playAfterDelayplayAfterRepeat在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()playAfterDelayplayAfterRepeatPause, 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 reachedAll stop methods fire (not ). Chained animations trigger after stop.
animationstopanimationcompletejs
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); // 播放到指定帧时停止所有停止方法都会触发事件(而非)。链式动画会在停止后触发。
animationstopanimationcompleteAnimation 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: , , , , , , . All share the same callback signature: .
animationstartanimationcompleteanimationcomplete-{key}animationupdateanimationstopanimationrepeatanimationrestart(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();
});可用事件:、、、、、、。所有事件的回调签名均为:。
animationstartanimationcompleteanimationcomplete-{key}animationupdateanimationstopanimationrepeatanimationrestart(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 (ms) that is added to the base msPerFrame.
durationjs
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
});单个帧可设置(毫秒),该时长会添加到基础帧时长中。
durationjs
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 animationsjs
// 可见性控制
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 namejs
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()
)
this.anims.create()AnimationConfig(用于this.anims.create()
)
this.anims.create()| Property | Type | Default | Description |
|---|---|---|---|
| string | -- | Unique identifier for the animation |
| string or AnimationFrame[] | | Texture key string (uses all frames) or array of frame config objects |
| boolean | | Numerically sort frames when using a string key |
| string | | Fallback texture key if not set per-frame |
| number | | Playback rate in frames per second (used if |
| number | | Total animation length in ms (derives frameRate if set) |
| boolean | | Skip frames when lagging behind |
| number | | Delay before playback starts (ms) |
| number | | Times to repeat after first play (-1 = infinite) |
| number | | Delay before each repeat (ms) |
| boolean | | Reverse back to start before repeating |
| boolean | | Show first frame immediately during delay period |
| boolean | | Set visible=true when animation starts |
| boolean | | Set visible=false when animation completes |
| boolean | | Start from a random frame |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| string | -- | 动画的唯一标识符 |
| string 或 AnimationFrame[] | | 纹理键字符串(使用所有帧)或帧配置对象数组 |
| boolean | | 使用字符串键时按数字排序帧 |
| string | | 若未为单帧设置纹理键,则使用此 fallback 纹理键 |
| number | | 播放帧率(每秒帧数,当 |
| number | | 动画总时长(毫秒,若设置则推导frameRate) |
| boolean | | 当动画滞后时跳过帧 |
| number | | 播放开始前的延迟(毫秒) |
| number | | 首次播放后重复的次数(-1 = 无限重复) |
| number | | 每次重复前的延迟(毫秒) |
| boolean | | 重复前反向播放至起始帧 |
| boolean | | 在延迟期间立即显示第一帧 |
| boolean | | 动画开始时设置visible=true |
| boolean | | 动画完成时设置visible=false |
| boolean | | 从随机帧开始播放 |
PlayAnimationConfig (used with sprite.play()
)
sprite.play()PlayAnimationConfig(用于sprite.play()
)
sprite.play()All AnimationConfig timing properties are available, plus:
| Property | Type | Default | Description |
|---|---|---|---|
| string or Animation | -- | Animation key or instance to play |
| number | | Frame index to begin playback from |
| number | | Speed multiplier for this playback |
Values in PlayAnimationConfig override the animation definition for this specific playback instance.
包含所有AnimationConfig的时间属性,额外增加:
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| string 或 Animation | -- | 要播放的动画键或实例 |
| number | | 播放的起始帧索引 |
| number | | 本次播放的速度乘数 |
PlayAnimationConfig中的值会覆盖动画定义中的对应值,仅对本次播放生效。
Duration vs FrameRate Priority
Duration与FrameRate优先级
- If both and
durationare null: defaults to 24 fps.frameRate - If only is set: frameRate is calculated as
duration.totalFrames / (duration / 1000) - If is set (even if duration is also set): frameRate wins, and duration is derived as
frameRate.(totalFrames / frameRate) * 1000
- 若和
duration均为null:默认使用24 fps。frameRate - 仅设置:frameRate会通过
duration计算得出。totalFrames / (duration / 1000) - 设置了(即使同时设置了duration):frameRate优先级更高,duration会通过
frameRate推导得出。(totalFrames / frameRate) * 1000
Events
事件
Sprite Event Flow
精灵事件流
- -- after delay expires, before first update
animationstart - -- each frame change
animationupdate - -- each repeat cycle
animationrepeat - -- natural end (finite repeat)
animationcomplete - -- same, with animation key appended
animationcomplete-{key}
Stopped manually: fires instead of complete. Restarted mid-play: fires.
animationstopanimationrestartAll callbacks: .
(animation, frame, gameObject, frameKey)- ——延迟结束后,首次更新前触发
animationstart - ——每帧变化时触发
animationupdate - ——每次重复循环时触发
animationrepeat - ——自然结束(有限重复)时触发
animationcomplete - ——同上,但仅针对指定键的动画
animationcomplete-{key}
手动停止时:触发而非complete事件。播放中途重启时:触发事件。
animationstopanimationrestart所有回调函数签名:。
(animation, frame, gameObject, frameKey)AnimationManager Events
AnimationManager事件
Fire on : , , , .
this.animsaddanimationremoveanimationpauseallresumeall在上触发:、、、。
this.animsaddanimationremoveanimationpauseallresumeallAPI Quick Reference
API速查
AnimationManager (this.anims
)
this.animsAnimationManager(this.anims
)
this.anims| Method | Description |
|---|---|
| Create and register a global animation |
| Remove a global animation by key |
| Get an Animation instance by key |
| Check if a key is already registered |
| Generate frame array from a spritesheet |
| Generate frame array from an atlas |
| Play an animation on an array of Game Objects |
| Staggered play across multiple Game Objects |
| Pause/resume all animations globally |
| Set transition delay between two animations |
| Remove a mix pairing |
| Get the mix delay between two animations |
| Create animations from Aseprite JSON |
| Export all animations as JSON data |
| Load animations from JSON data (pass |
| 方法 | 描述 |
|---|---|
| 创建并注册全局动画 |
| 通过键删除全局动画 |
| 通过键获取Animation实例 |
| 检查键是否已注册 |
| 从精灵表生成帧数组 |
| 从图集生成帧数组 |
| 在一组游戏对象上播放动画 |
| 在多个游戏对象上交错播放动画 |
| 全局暂停/恢复所有动画 |
| 设置两个动画之间的过渡延迟 |
| 删除过渡配对 |
| 获取两个动画之间的过渡延迟 |
| 从Aseprite JSON创建动画 |
| 将所有动画导出为JSON数据 |
| 从JSON数据加载动画(传入 |
AnimationState (sprite.anims
)
sprite.animsAnimationState(sprite.anims
)
sprite.anims| Method | Description |
|---|---|
| Play an animation |
| Play an animation in reverse |
| Play after a delay in ms |
| Play after current anim repeats N times |
| Queue animation(s) to play after current one |
| Stop immediately |
| Stop after a delay in ms |
| Stop after N more repeats |
| Stop when a specific frame is reached |
| Pause playback |
| Resume playback |
| Restart from beginning |
| Reverse direction mid-playback |
| Get the current animation key |
| Get the current frame key |
| Get progress 0-1 |
| Set progress 0-1 |
| Change repeat count during playback |
| Get total frame count |
| Create a local animation on this sprite |
| Check if a local animation exists |
| Get a local animation by key |
Key properties: , , , , , , .
isPlayinghasStartedcurrentAnimcurrentFrameforwardinReversetimeScale| 方法 | 描述 |
|---|---|
| 播放动画 |
| 反向播放动画 |
| 延迟指定毫秒后播放 |
| 当前动画重复N次后播放 |
| 队列化动画,在当前动画结束后播放 |
| 立即停止 |
| 延迟指定毫秒后停止 |
| 再重复N次后停止 |
| 播放到指定帧时停止 |
| 暂停播放 |
| 恢复播放 |
| 从开头重启 |
| 播放过程中反转方向 |
| 获取当前动画的键 |
| 获取当前帧的键 |
| 获取播放进度(0-1) |
| 设置播放进度(0-1) |
| 播放过程中修改重复次数 |
| 获取总帧数 |
| 在当前精灵上创建本地动画 |
| 检查本地动画是否存在 |
| 通过键获取本地动画 |
关键属性:、、、、、、。
isPlayinghasStartedcurrentAnimcurrentFrameforwardinReversetimeScaleGotchas
注意事项
- Animations are global by default. registers across all Scenes. Do not recreate in every Scene -- it logs a warning and returns the existing one.
this.anims.create() - never fires
repeat: -1. Useanimationcompleteto end infinite animations. Listen forstop()instead.animationstop - beats
frameRate. If both are set, frameRate wins. Set onlyduration(leave frameRate null) to control total length.duration - Per-frame is additive. Added on top of base msPerFrame, not a replacement.
duration - stops the current animation (fires
play()). Useanimationstopto skip if already playing.play(key, true) - Mix delays only work with .
play()/playAfterDelaybypass mixes.playAfterRepeat - Local animations override global. Same key on a sprite's local map takes priority.
- Sprite shorthand methods. ,
sprite.play(),sprite.playReverse(),sprite.chain()wrapsprite.stop().sprite.anims.* - Chained anims fire after stop too. Clear the queue with before stopping if unwanted.
sprite.anims.chain() - end=-1 means last frame. The
generateFrameNumbersframe is excluded automatically.__BASE
- 动画默认是全局的。会在所有场景中注册动画。不要在每个场景中重复创建——这会触发警告并返回已存在的动画。
this.anims.create() - 永远不会触发
repeat: -1。使用animationcomplete结束无限循环动画,监听stop()事件。animationstop - 优先级高于
frameRate。若两者都设置,frameRate生效。仅设置duration(留空frameRate)以控制总时长。duration - 单帧是累加的。是在基础帧时长之上增加,而非替换。
duration - 会停止当前动画(触发
play())。使用animationstop可在已播放时忽略调用。play(key, true) - 过渡延迟仅对生效。
play()/playAfterDelay会绕过过渡延迟。playAfterRepeat - 本地动画覆盖全局动画。精灵本地动画映射中同名的键优先级更高。
- 精灵快捷方法。、
sprite.play()、sprite.playReverse()、sprite.chain()是sprite.stop()的封装。sprite.anims.* - 链式动画在停止后也会触发。若不需要,可在停止前调用清空队列。
sprite.anims.chain() - 的end=-1表示最后一帧。
generateFrameNumbers帧会自动排除。__BASE
Source File Map
源文件映射
| File | Purpose |
|---|---|
| Global singleton -- create, remove, get, generateFrame*, mix, staggerPlay |
| Animation definition -- frames, timing, yoyo, repeat logic |
| Per-sprite component -- play, stop, pause, chain, events |
| Single frame data -- textureKey, textureFrame, duration, progress |
| All animation event constants |
| AnimationConfig typedef |
| PlayAnimationConfig typedef |
| Config for generateFrameNumbers |
| Config for generateFrameNames |
| 文件 | 用途 |
|---|---|
| 全局单例——创建、删除、获取、generateFrame*、过渡混合、交错播放 |
| 动画定义——帧、时间、往返播放、重复逻辑 |
| 单精灵组件——播放、停止、暂停、链式动画、事件 |
| 单帧数据——纹理键、纹理帧、时长、进度 |
| 所有动画事件常量 |
| AnimationConfig类型定义 |
| PlayAnimationConfig类型定义 |
| generateFrameNumbers的配置类型定义 |
| generateFrameNames的配置类型定义 |