Managing multiple scenes is a fundamental aspect of structuring games in Phaser. Scenes allow you to separate different parts of your game, such as menus, levels, and game over screens, into modular, manageable components. This section will guide you through the concepts, practical implementation, and best practices for working with multiple scenes in Phaser.


  1. What is a Scene in Phaser?

A scene in Phaser is a self-contained section of your game. Each scene manages its own assets, logic, and display objects. Common examples include:

  • Boot Scene: Loads assets and prepares the game.
  • Menu Scene: Displays the main menu.
  • Game Scene: Contains the main gameplay.
  • Game Over Scene: Shows when the player loses.

Benefits of Using Multiple Scenes:

  • Organization: Keeps code modular and easier to maintain.
  • Separation of Concerns: Each scene handles a specific part of the game.
  • Reusability: Scenes can be reused or rearranged as needed.

  1. Creating and Configuring Scenes

Defining a Scene

A scene is typically a JavaScript class that extends Phaser.Scene. Here’s a basic example:

class MainMenu extends Phaser.Scene {
  constructor() {
    super({ key: 'MainMenu' });
  }

  preload() {
    // Load assets for the menu
  }

  create() {
    // Set up menu UI
    this.add.text(100, 100, 'Main Menu', { fontSize: '32px', fill: '#fff' });

    // Start the GameScene when the user clicks
    this.input.once('pointerdown', () => {
      this.scene.start('GameScene');
    });
  }
}

Explanation:

  • super({ key: 'MainMenu' }): Assigns a unique key to the scene.
  • preload(): Loads assets needed for this scene.
  • create(): Sets up the scene’s objects and logic.

Adding Multiple Scenes to the Game

You can add multiple scenes when creating your Phaser game instance:

const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: [MainMenu, GameScene, GameOverScene]
};

const game = new Phaser.Game(config);

Table: Scene Lifecycle Methods

Method Purpose
preload Load assets before the scene starts
create Set up objects and logic
update Runs every frame for game logic
init Initialize data before preload/create
shutdown Cleanup before the scene is stopped
destroy Cleanup when the scene is destroyed

  1. Switching Between Scenes

Phaser provides several methods to control scenes:

  • this.scene.start('SceneKey'): Stops the current scene and starts another.
  • this.scene.stop('SceneKey'): Stops a specific scene.
  • this.scene.pause('SceneKey'): Pauses a scene.
  • this.scene.resume('SceneKey'): Resumes a paused scene.
  • this.scene.launch('SceneKey'): Starts a scene without stopping the current one (useful for overlays like HUDs).

Example: Switching from Menu to Game

// In MainMenu scene
this.input.once('pointerdown', () => {
  this.scene.start('GameScene');
});

Example: Overlaying a HUD Scene

// In GameScene
this.scene.launch('HUDScene');

  1. Passing Data Between Scenes

You can pass data when starting a new scene:

// Starting GameScene with data
this.scene.start('GameScene', { level: 2, score: 100 });

In the target scene, access the data in the init method:

class GameScene extends Phaser.Scene {
  init(data) {
    this.level = data.level;
    this.score = data.score;
  }
}

  1. Practical Example: Basic Scene Flow

Let’s create a simple flow: Main Menu → Game → Game Over.

MainMenu Scene

class MainMenu extends Phaser.Scene {
  constructor() {
    super({ key: 'MainMenu' });
  }
  create() {
    this.add.text(300, 250, 'Click to Start', { fontSize: '32px', fill: '#fff' });
    this.input.once('pointerdown', () => {
      this.scene.start('GameScene');
    });
  }
}

GameScene

class GameScene extends Phaser.Scene {
  constructor() {
    super({ key: 'GameScene' });
  }
  create() {
    this.add.text(300, 250, 'Playing Game...', { fontSize: '32px', fill: '#fff' });
    // Simulate game over after 3 seconds
    this.time.delayedCall(3000, () => {
      this.scene.start('GameOverScene', { score: 42 });
    });
  }
}

GameOverScene

class GameOverScene extends Phaser.Scene {
  constructor() {
    super({ key: 'GameOverScene' });
  }
  init(data) {
    this.finalScore = data.score;
  }
  create() {
    this.add.text(300, 200, 'Game Over', { fontSize: '32px', fill: '#fff' });
    this.add.text(300, 250, `Score: ${this.finalScore}`, { fontSize: '24px', fill: '#fff' });
    this.add.text(300, 300, 'Click to Restart', { fontSize: '24px', fill: '#fff' });
    this.input.once('pointerdown', () => {
      this.scene.start('MainMenu');
    });
  }
}

  1. Exercise: Create a Pause Menu Scene

Task:
Add a "Pause" feature to your game. When the player presses the "P" key, pause the game and show a PauseMenu scene. Pressing "P" again resumes the game.

Steps:

  1. Create a PauseMenu scene that displays "Paused".
  2. In your GameScene, listen for the "P" key.
  3. When "P" is pressed, pause GameScene and launch PauseMenu.
  4. In PauseMenu, listen for "P" to resume the game.

Solution:

// PauseMenu Scene
class PauseMenu extends Phaser.Scene {
  constructor() {
    super({ key: 'PauseMenu' });
  }
  create() {
    this.add.text(350, 250, 'Paused', { fontSize: '32px', fill: '#fff' });
    this.input.keyboard.on('keydown-P', () => {
      this.scene.stop();
      this.scene.resume('GameScene');
    });
  }
}

// In GameScene
create() {
  // ... existing code ...
  this.input.keyboard.on('keydown-P', () => {
    this.scene.launch('PauseMenu');
    this.scene.pause();
  });
}

Common Mistakes & Tips:

  • Forgetting to resume the game scene: Make sure to call this.scene.resume('GameScene') in the PauseMenu.
  • Multiple event listeners: Use once or remove listeners to avoid stacking them.
  • Scene keys: Always use unique keys for each scene.

  1. Summary

  • Scenes are modular sections of your game, each with its own logic and assets.
  • You can add multiple scenes to your game and control their flow using methods like start, stop, pause, and launch.
  • Data can be passed between scenes using the init method.
  • Overlay scenes (like HUDs or pause menus) can run simultaneously with gameplay scenes.
  • Proper scene management leads to cleaner, more maintainable code and a better game structure.

Next Steps:
In the next topic, you’ll learn how to save and load game state, allowing players to continue their progress across sessions.

© Copyright 2024. All rights reserved