Creating Your First Scene in Phaser 4
Introduction
In Phaser 4, Scenes are the building blocks of your game. A scene represents a distinct state or screen in your project—such as a loading screen, a main menu, a gameplay level, or a "Game Over" screen.
Phaser 4 uses ES6 Classes to structure scenes, keeping your codebase modular, scalable, and easy to maintain. If you want to understand how the scene fits into the full project structure, start with our guide on understanding the Phaser 4 game configuration object.
The Anatomy of a Phaser 4 Scene Class
Every scene in your game extends the base Phaser.Scene class. It relies on a specific sequence of built-in methods—known as the lifecycle hooks—to manage loading, rendering, and logic loops.
Here is the standard structure of a scene file (e.g., MainScene.js):
export default class MainScene extends Phaser.Scene {constructor() {// Assign a unique key to identify this scene within the enginesuper({ key: 'MainScene' });}preload() {// 1. Load assets (images, audio, spritesheets, JSON) before the scene startsconsole.log('Preload: Loading assets...');}create() {// 2. Instantiate game objects (sprites, text, physics bodies)console.log('Create: Instantiating objects...');}update(time, delta) {// 3. The Game Loop: Runs every frame (input, movement, collisions)}}
Detailed Breakdown of the Scene Lifecycle Hooks
To build games effectively, you must understand exactly when and why each lifecycle method runs:
1. preload()
Before a scene is visible, Phaser executes the preload() method. This is where you queue files to be downloaded into the browser’s memory. Doing this prevents visual lag or missing assets when the game begins.
preload() {// Load an image asset and assign it the key 'background'this.load.image('background', 'assets/images/space.png');this.load.image('player', 'assets/sprites/ship.png');}
2. create()
The create() method runs exactly once after all assets queued in preload() have finished downloading. This is where you set up your scene layout, assign physics properties, and register keyboard or mouse inputs.
create() {// Add the background image to the center of the canvasthis.add.image(400, 300, 'background');// Add the player sprite (stored as a class property to access in update)this.player = this.add.image(400, 500, 'player');// Add a UI text elementthis.scoreText = this.add.text(16, 16, 'Score: 0', {fontSize: '24px',color: '#ffffff'});}
3. update(time, delta)
The update() method is the heart of your game loop. It runs continuously, typically matching the refresh rate of the player's monitor (usually 60 times per second or 60 FPS). Any code that needs to react to real-time events goes here.
- time: The current timestamp (in milliseconds).
- delta: The time elapsed since the last frame (in milliseconds).
update(time, delta) {// Example: Slowly rotate the player sprite every frameif (this.player) {this.player.rotation += 0.01;}}
Registering and Starting Your Scene
Creating a scene class does not automatically load it into the engine. You must register it in your Game Configuration Object. Phaser will automatically start the first scene listed in the array.
import MainScene from './MainScene.js';const config = {type: Phaser.AUTO,width: 800,height: 600,parent: 'game-container',// Register your scene here:scene: [MainScene]};const game = new Phaser.Game(config);
Best Practices for Phaser 4 Scenes
1. Maintain Unique Scene Keys
The string key passed to super({ key: 'MainScene' }) must be completely unique across your entire game. You will use these keys to transition between scenes:
// Switches from the current scene to the LevelTwo scenethis.scene.start('LevelTwo');
2. Watch the Rendering Order (Z-Indexing)
In Phaser, game objects are drawn on screen in the order they are created. An image created on line 5 will be drawn behind an image created on line 6. Always render your backgrounds first, followed by platforms, players, and finally UI elements.
3. Keep One Scene Per File
As your game grows, write each scene in its own file and use standard JavaScript ES6 export default statements. This makes debugging much easier and prevents merge conflicts in larger projects.
FAQ
What is a scene in Phaser 4?
In Phaser 4, a scene is a distinct state or screen in a game, such as a loading screen, main menu, gameplay level, or game over screen.
What are the lifecycle methods of a Phaser 4 scene?
The core lifecycle methods are preload() for loading assets, create() for setting up the scene, and update() for the frame-by-frame game loop.
How do I register a scene in Phaser 4?
You register a scene inside the Game Configuration Object using the scene array, and Phaser automatically starts the first scene in that list.
Conclusion
Scenes are one of the most important parts of Phaser 4 game architecture. Once you understand how preload(), create(), and update() work together, you can build cleaner and more scalable games.
If you want to continue the flow, go back to understanding the Phaser 4 game configuration object to see how scenes are registered and booted inside the engine.