This blog post is part of a series on Phaser. Click here to read the first post.

To create and play an animation on a sprite in Phaser, you need to follow a few steps.

Firstly, you have to load a sprite sheet. A sprite sheet is an image that contains multiple sprites. Specify the width and height of each sprite in the sheet. For example:

this.load.spritesheet('dog', 'dog.png', {
 frameWidth: 20,
 frameHeight: 20
});

Once the sprite sheet is loaded, you can generate an animation using this.anims.create(). Provide a key for the animation, specify the frames to use from the sprite sheet, set the frame rate, and determine if the animation should repeat indefinitely or just play once. Here’s an example:

this.anims.create({
 key: 'animate_dog',
 frames: this.anims.generateFrameNames('dog'),
 frameRate: 20,
 repeat: -1
});

To start the animation, call the play() method on the sprite:

this.ship1.play('ship1_anim');

By default, the animation will repeat indefinitely. If you want the animation to play just once and hide the sprite sheet when it’s done, add these options:

repeat: 0,
hideOnComplete: true

You can also specify a range of frames to iterate through instead of using all the frames from the sprite sheet. This is useful when you have a large sprite sheet with multiple objects:

frames: this.anims.generateFrameNames('dog', {
 start: 0,
 end: 2
})

These are the basic steps to create and play animations in Phaser. Have fun experimenting and adding life to your sprites!

Tags: Phaser, Animation, Sprite Sheet