Sprite Sheets are a great way to reduce the number of image requests and quickly swap textures for elaborate animations. There are many ways to create sprite sheets, but the easiest approach is using a tool. I like Texture Packer, which has a free trial. To use it you simply drag in the images you want to combine and specify the pixi.js format.
Once you have your sprite sheet and json, you can load them just like any other asset with the pixi loader.
let loader = PIXI.Loader.shared;
loader.add("guy", "guy.json");
This gives you access to the texture you can use in the AnimatedSprite class. You can access it on the animations
property of the sprite sheet, using the name of the file you used to export. The file name I used to generate the sprite sheet in this case was pixels_large
.
let texture = loader.resources.guy.spritesheet;
let sprite = new PIXI.AnimatedSprite(texture.animations.pixels_large);
From here you have some special methods you can call on the sprite to play the animation.
sprite.play();
You can also set the speed of the animation with the animationSpeed
property.
sprite.animationSpeed = 0.1;
You can make the animation loop by setting the loop
property to true
.
sprite.loop = true;
You also have some callback methods you can access to respond to various events in the animation. These callbacks trigger when the frame changes, animation completes, or the animation loops.
sprite.onLoop = () => {
console.log('loop');
}
sprite.onFrameChange = () => {
console.log('currentFrame', sprite.currentFrame);
}
sprite.onComplete = () => {
console.log('done');
}
The AnimatedSprite
class is pretty basic, so for complex animations or sequencing it is best to either have multiple AnimatedSprites inside a container and manage their playback and visibility, or create your own class that extends PIXI.Sprite
and swaps the texture.
You can download the files for the demo here.