/

Phaser: Understanding the Game Loop

Phaser: Understanding the Game Loop

This blog post is part of a series on Phaser. Check out the first post here.

In Phaser, we have three different scenes: preload(), create(), and update(). While preload() and create() are run only once, update() is constantly called in an never-ending loop until the game ends.

In this example, we create a text object that slowly moves towards the bottom right corner of the canvas:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let text;

function create() {
text = this.add.text(100, 100, 'test');
}

function update() {
text.x += 1;
text.y += 1;
}

const game = new Phaser.Game({
width: 400,
height: 400,
scene: {
create,
update
}
});

Note that I added let text at the top so we can reference it within both create() and update() functions.

In the update() function, I modified the values of x and y properties. You can also modify other properties, such as angle to rotate an object:

1
2
3
function update() {
text.angle += 2;
}

Additionally, you can set the initial velocity of an object using the setVelocity() function:

1
text.setVelocity(20, 20);

Alternatively, you can use setVelocityX() and setVelocityY() to set velocity on only one axis.