Phaser: Scenes
By Flavio Copes
Learn how scenes work in Phaser through the preload, create, and update functions you pass to the scene property to load assets and build your game.
This post is part of a Phaser series. Click here to see the first post of the series.
Scenes are where we define our game. A scene is a self-contained piece of it: the loading screen, the menu, a level. We pass the scene as a property of the configuration object.
In its simplest form, a scene is an object with up to 3 functions:
preloadis the function where we load external assets, like images and soundscreateis called once when the scene starts, and here we define the GameObjects needed at the start of the gameupdateis the game event loop, where we define how the game works
GameObjects are a particular type of Phaser objects: images, sprites, text, and everything else you put on screen.
Here’s an example of the first 2 events mentioned:
function preload() {}
function create() {}
new Phaser.Game({
width: 450,
height: 600,
scene: {
preload: preload,
create: create
}
})
Or, since each property in this case has the same name of the function:
new Phaser.Game({
width: 450,
height: 600,
scene: {
preload,
create
}
})
What goes in each function?
Inside these functions, this refers to the scene. This gives us access to everything the scene provides: this.load to load assets, this.add to create GameObjects, and much more.
The typical flow is to load an image in preload, then use it in create:
function preload() {
this.load.image('ball', 'assets/ball.png')
}
function create() {
this.add.image(225, 300, 'ball')
}
this.load.image() takes a key and a file path. The key ('ball') is how we reference the asset later. this.add.image() takes the x and y coordinates, and the key of the image to show.
The order is guaranteed. Phaser waits until everything queued in preload finishes downloading before it calls create, so the image is ready when we use it.
update runs continuously, once per frame, usually 60 times per second. Movement, input checks and collisions go here:
function update() {
//runs on every frame
}
Be careful with asset keys. If you add an image with a key you never loaded, Phaser doesn’t crash: it shows a green placeholder box instead of your image, and logs a warning in the console. When you see that box, check the key in create matches the one in preload, and check the file path is correct.
Scenes as classes
When the game grows, an object with 3 functions gets crowded. You can also define a scene as a class extending Phaser.Scene:
class MainScene extends Phaser.Scene {
preload() {
this.load.image('ball', 'assets/ball.png')
}
create() {
this.add.image(225, 300, 'ball')
}
}
new Phaser.Game({
width: 450,
height: 600,
scene: MainScene
})
Same 3 functions, but now the scene has a place for its own methods and properties.
A game can have multiple scenes, too. Pass an array, and the first one starts automatically:
scene: [MenuScene, MainScene]