/

Phaser: Animations

Phaser: Animations

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:

1
2
3
4
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:

1
2
3
4
5
6
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:

1
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:

1
2
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:

1
2
3
4
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