🛸 Phaser

Updated at 2024-04-17 07:47

Scene is the main high-level building block of a Phaser game. Scene is a collection of game objects and surrounding logic. You can have as many running scenes as you want. You usually split your game to e.g. the gameplay scene and the user interface overlay scene.

Each scene has five core callback methods that you override:

  • constructor: is ran once when the scene is defined, useful for initializing variables.
  • init: is run each time the scene starts, allows e.g., switching to another Scene before any loading happens or receiving startup information from other scenes.
  • preload: is run after init is used to load assets like images with this.load.
  • create: is run after preload and used to create game objects with this.add as assets are now available.
  • update: is run once on each game loop if scene is active.

You can use a Scene constructor files property which will be loaded before preload. These constructor files are good for either simple graphics required for a loading screen or small configuration files required to determine which assets to download in preload.

class BootScene extends Phaser.Scene {
    constructor() {
            key: SceneName.Boot,
            files: {
                type: 'image',
                key: 'background',
                url: 'assets/background.png'

Note that init, preload and create can be called again sometime later. For example, if you do stop() and sometime later start()/launc() on the scene.

The first listed scene in the game config is started automatically.

new Phaser.Game({
    scenes: [SceneThisOne1, Scene2, Scene3],

this.scene is the scene manager. It is a global helper to manage scenes. "this" is the current scene in a normal Phaser context, or the related game object in a game object context.

You add scenes with this.scene.add if it was not included in the config. But they are not automatically started. You start scenes with start (that also stops the current scene) or launch (which doesn't stop the current scene.)

You can destroy scenes with this.scene.remove(). Or pause them with pause() (doesn't call update each loop) or make them inactive with stop() (the next start will rerun the initialization methods).

Scenes share a global Cache. All scenes use the same, potentially cached, files.

Scenes share a global Registry which is a DataManager. So this.registry can be used for cross-scene communication.

Each scene has core plugins that can't be removed:

  • An Event Emitter
  • The 2D Camera Manager
  • The Game Object Creator
  • The Game Object Factory
  • The Scene Plugin
  • The Display List
  • The Update List

Each scene has some plugins that can be removed in the constructor:

  • The 3D Camera Manager
  • The Clock
  • The Data Manager Plugin
  • The Input Plugin
  • The Loader Plugin
  • The Tween Manager
  • The Lights Plugin