How to Make Multiple Scenes in Phaser 3
You can create multiple scenes in Phaser 3, by simply using an array for the scene
property in your config
, when you create the game:
const config = {
width: window.innerWidth,
height: window.innerHeight,
physics: {
default: 'arcade'
},
scene: [
Boot,
Menu,
Game
]
};
new Phaser.Game(config);
The scenes you define will be loaded in order, meaning that for the example above, first the Boot
scene will be loaded, then the Menu
, and lastly, the Game
. You can think of scenes as separate stages of a game. A common practice is to create different scenes for the boot screen, for the main menu, the game itself, or a scene for different views, such as a world map. Scenes have four different built-in methods you can use:
class Boot extends Phaser.Scene {
constructor () {
super('Boot');
}
init() {
// Used to prepare data
}
preload() {
// Used for preloading assets into your scene, such as
// β’ images
// β’ sounds
}
create(data) {
// Used to add objects to your game
}
update(time, delta) {
// Used to update your game. This function runs constantly
}
}
export default Boot;
Note that for the constructor
, you have to call super
where you pass an identifier. This is what the name of your scene will be, and this is how you can reference it later on.
You can create as many scenes as you want, and you can also add scenes dynamically from other scenes with this.scene.add
.
this.scene.add('Main');
To switch between scenes, all you have to do is call this.scene.start
, passing the identifier of the scene you want to start.
this.scene.start('Main');
And lastly, you also have the option to play multiple scene simultaneously.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: