/

Phaser: Sprites

Phaser: Sprites

Welcome back to the Phaser series! In the previous post, we learned how to add images to our Phaser game. If you missed it, you can check it out here.

In this post, we will explore another important GameObject in Phaser - sprites. Sprites are similar to images, but they have one key difference - they can be animated!

Let’s start by adding a sprite to our game. First, we need to preload the sprite in the preload function:

1
2
3
function preload() {
this.load.spritesheet('dog', 'dog.png', { frameWidth: 64, frameHeight: 64 });
}

In the code above, we use the load.spritesheet method to load the sprite. We provide the key as 'dog' and the path to the sprite image file as 'dog.png'. Additionally, we specify the dimensions of each frame of the sprite using the frameWidth and frameHeight parameters.

Next, we can create the sprite in the create function:

1
2
3
function create() {
this.add.sprite(400, 200, 'dog').play('dogAnimation');
}

Here, we use the add.sprite method to create the sprite at the coordinates (400, 200). We pass the key 'dog' to specify which sprite to use. Additionally, we call the play method and provide the name of the animation we want to play, which in this case is 'dogAnimation'.

To animate the sprite, we need to define the animation. This can be done in the create function or in a separate createAnimations function:

1
2
3
4
5
6
7
8
9
10
function create() {
// ...

this.anims.create({
key: 'dogAnimation',
frames: this.anims.generateFrameNumbers('dog', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
}

In the code above, we use the anims.create method to create the animation. We provide a unique key for the animation as 'dogAnimation'. The frames parameter defines the sequence of frames to use for the animation. In this example, we use frames 0 to 3 of the 'dog' sprite. The frameRate parameter specifies the speed of the animation, and the repeat parameter determines how many times the animation should repeat (-1 means it repeats indefinitely).

And that’s it! You have successfully added an animated sprite to your Phaser game. Feel free to experiment with different sprites and animations to make your game even more dynamic and interactive.

Stay tuned for the next post in the Phaser series, where we will explore more exciting features of this powerful game development framework.

Tags: Phaser, Sprites, Game Development, Animation