animations

Use this skill when creating or controlling sprite animations in Phaser 4. Covers spritesheets, atlases, AnimationManager, AnimationState, play/stop/chain, frame callbacks, and animation events. Triggers on: sprite animation, spritesheet, play animation, animation frames.

By phaserjs · 686 installs

npx skills add phaserjs/phaser --skill animations

Source repository · Upstream listing

Phaser 4 Sprite Animations 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 Quick Start Core Concepts AnimationManager vs AnimationState Phaser has two distinct animation objects: Aspect AnimationManager AnimationState Access this.anims (in a Scene) or this.game.anims sprite.anims Scope Global shared across all scenes Per sprite instance Purpose Create/store animation definitions Control 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). Local vs Global Animations 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. Common Patterns Spritesheet Animation Use generateFrameNumbers for spritesheets (numeric frame indices). 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) Atlas Animation Use generateFrameNames for texture atlases (string based frame names). 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. 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. Yoyo and Repeat When yoyo is true, the animation plays forward then reverses. The full cycle counts as one play. Chaining Animations Chaining is per sprite. Chained animations start after animationcomplete or animationstop . An animation with repeat: 1 never completes call stop() to trigger the chain. Playing in Reverse playReverse sets forward = false and inReverse = true . The reverse() method toggles direction mid playback. Play Variants Animation Mixing Adds a transition delay between two specific animations, set globally on the AnimationManager. Mix delays only apply with sprite.play() , not playAfterDelay or playAfterRepeat . Pause, Resume, and Stop All stop methods fire animationstop (not animationcomplete ). Chained animations trigger after stop. Animation Events Available events: animationstart , animationcomplete , animationcomplete {key} , animationupdate , animationstop , animationrepeat , animationrestart . All share the same callback signature: (animation, frame, gameObject, frameKey) . Frame Level Callbacks via animationupdate Per Frame Duration Individual frames can have a duration (ms) that is added to the base msPerFrame. Visibility, Random Start, and TimeScale Staggered Playback JSON Export and Import Modifying Animation Frames at Runtime Aseprite Support Configuration Reference AnimationConfig (used with this.anims.create() ) Property Type Default Description 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 PlayAnimationConfig (used with sprite.play() ) All AnimationConfig timing properties are available, plus: Property Type Default Description 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. Duration vs FrameRate Priority 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 . 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) . AnimationManager Events Fire on this.anims : addanimation , removeanimation , pauseall , resumeall . API Quick Reference AnimationManager ( this.anims ) Method Description 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) AnimationState ( sprite.anims ) Method Description 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 . 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. Source File Map File Purpose 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