How to Make Multiple Scenes in Phaser 3

How to Make Multiple Scenes in Phaser 3

Ferenc Almasi β€’ πŸ”„ 2021 July 13 β€’ πŸ“– 2 min read

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);
phaser.js
Copied to clipboard!

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;
Boot.js
Copied to clipboard!

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');
Scene.js
Copied to clipboard!

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');
Scene.js
Copied to clipboard!

And lastly, you also have the option to play multiple scene simultaneously.

Building The Game Breakout Using JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended