Phaser: The game loop
By Flavio Copes
Learn how the Phaser game loop works through the update function that runs forever, moving objects by changing x and y or calling setVelocity.
This post is part of a Phaser series. Click here to see the first post of the series.
The game loop in Phaser is the update() function. In addition to preload() and create(), it’s the third function we can define in a scene.
Here is where everything happens.
preload() and create() are run just once.
update() is going to be called forever. It’s a never ending loop, repeatedly called until our game ends. On a typical monitor it runs 60 times per second, once per frame.
This is the heart of every game. You read the input, move objects a tiny bit, check what happened. Then the next frame does it all again. Movement in games is just many small changes, applied very fast.
In this example, we create a text that slowly moves to the bottom right of the canvas:
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 how I added let text at the top, so we can reference it inside both create() and update(). This is a common pattern. Objects created in create() must be stored somewhere update() can reach them.
In update() I modified the x and y properties. You can modify other properties, for example you can modify angle to rotate an object:
function update() {
text.angle += 2
}
Using time and delta
Phaser calls update() with two arguments:
function update(time, delta) {
}
time is the number of milliseconds since the game started. delta is the number of milliseconds since the last frame, around 16.6 at 60 frames per second.
Why does this matter? Moving by 1 pixel per frame ties your game speed to the frame rate. On a 120Hz display the text moves twice as fast. That’s a classic pitfall.
The fix is to scale movement by delta:
function update(time, delta) {
text.x += 0.06 * delta
}
Now the text moves 60 pixels per second, on any display.
Moving objects with velocity
Instead of moving objects by hand in update(), you can give them a velocity and let Phaser move them for you.
This works on physics-enabled objects, so you need arcade physics in the game config and a physics sprite:
const ball = this.physics.add.sprite(100, 100, 'ball')
ball.setVelocity(20, 20)
Call setVelocity() and pass a number for the X axis, and another optional one for the Y axis. The values are pixels per second.
Or use setVelocityX() and setVelocityY() to only set one of the 2 axes.