Control AnimatedSprite Speed and Loop in Pixi.js
This article provides a straightforward guide on how to adjust the
playback speed and configure the looping behavior of an
AnimatedSprite in Pixi.js. You will learn how to use the
animationSpeed property to control how fast your animations
run, and how to use the loop property to determine whether
your animations repeat or play only once.
Controlling Playback Speed
In Pixi.js, the playback speed of an AnimatedSprite is
controlled using the animationSpeed property. This property
acts as a multiplier for the frame update rate.
- Default Speed: The default value is
1, which plays the animation at the normal rate (aligned with the Pixi.js ticker, targeting 60 frames per second). - Slowing Down: Setting
animationSpeedto a value between0and1slows down the animation. For example,0.5plays the animation at half speed. - Speeding Up: Setting
animationSpeedto a value greater than1speeds up the animation. For example,2plays the animation at double speed. - Reverse Playback: You can use negative values
(e.g.,
-1) to play the animation in reverse.
// Create the animated sprite
const character = new PIXI.AnimatedSprite(textureArray);
// Play at half speed
character.animationSpeed = 0.5;
// Start playback
character.play();Configuring Looping Behavior
To control whether an animation repeats indefinitely or plays only
once, use the loop property.
- Looping (Default): The
loopproperty is set totrueby default, meaning the animation will start over from the first frame once it reaches the end. - Single Playthrough: Set
looptofalseif you want the animation to stop automatically on the final frame.
// Disable looping
character.loop = false;When loop is set to false, you can use the
onComplete callback function to trigger specific actions as
soon as the animation finishes.
character.onComplete = () => {
console.log("Animation has finished playing!");
// Perform cleanup or transition to another state
};Direct Playback Control
In addition to speed and looping, you can manually control the playback state using these built-in methods:
character.play(): Starts playing the animation from the current frame.character.stop(): Pauses the animation.character.gotoAndPlay(frameNumber): Jumps to a specific frame index and starts playing.character.gotoAndStop(frameNumber): Jumps to a specific frame index and pauses.