360 Secure SkillHub
360 安全技能中心

scenes

提供 Phaser 4 场景系统的开发参考,覆盖 init/preload/create/update 生命周期、场景配置、this.scene 的启动/重启/休眠/切换、并行场景与渲染顺序、跨场景数据传递,以及 SHUTDOWN 清理和过渡效果,并用代码示例纠正 v3 习惯。

分类:知识
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:30

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/scenes
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
scenes
description
Phaser 4 Scenes: the lifecycle (init, preload, create, update), the Scene config, this.scene (start, restart, launch, run, pause, resume, sleep, wake, switch, stop, transition, get), passing data, parallel Scenes, render order, and cleaning up on SHUTDOWN. Use when adding a menu, level, HUD, pause screen or game-over screen, restarting a level, running a UI Scene over the game, passing a score between Scenes, or fading from one Scene to the next. Corrects v3 habits: listeners on this.events, the registry, this.scale and other Scenes survive a restart and pile up; data given to wake or resume never reaches init or create; restart() with no data reuses the old data; launch or run on a running Scene restarts it; map replaces the whole injection map. Triggers on: Scene, this.scene, scene.start, restart, launch, pause, sleep, switch, transition, init, preload, create, update, SHUTDOWN, UI scene, HUD scene, multiple scenes.
metadata
{"phaser-version":"4.3.0"}

Scenes

How Scenes start and stop, how to run several at once, pass data between them, and clean up when one shuts down.

Source: src/scene/ScenePlugin.js (this.scene), src/scene/SceneManager.js, src/scene/Systems.js (this.sys), src/scene/Settings.js, src/scene/typedefs/SettingsConfig.js, src/scene/events/. Related: phaser4-core, game-setup-and-config, events-system, data-manager, loading-assets.

Quick start

class Level extends Phaser.Scene
{
    constructor ()
    {
        super('Level');
    }

    init (data)
    {
        //  Runs on every start and restart. Reset state here, not in the constructor
        this.level = data.level ?? 1;
        this.lives = 3;
    }

    preload ()
    {
        this.load.image('player', 'assets/player.png');
    }

    create ()
    {
        this.player = this.add.image(this.scale.width / 2, this.scale.height / 2, 'player');

        this.input.keyboard.once(Phaser.Input.Keyboard.Events.KEY_DOWN + 'N', () =>
        {
            this.scene.restart({ level: this.level + 1 });
        });
    }

    update (time, delta)
    {
        this.player.rotation += 0.001 * delta;
    }
}

new Phaser.Game({ width: 1024, height: 768, scene: [ Level ] });

Lifecycle

  1. constructor runs once, when the Scene is added.
  2. init(data) runs on every start. START and READY are emitted on this.events just before it.
  3. preload(), then the Loader runs. Files in the Scene config's pack are loaded before preload.
  4. create(data), after loading. With no preload, it runs straight after init. CREATE is emitted after it.
  5. update(time, delta) every frame while the Scene is running.

The status is this.sys.getStatus(): Phaser.Scenes.PENDING (0), INIT, START, LOADING, CREATING, RUNNING (5), PAUSED, SLEEPING, SHUTDOWN, DESTROYED (9).

The Scenes in the game config start when the game emits READY, after the global plugins are installed, and before callbacks.postBoot runs. Since 4.3, that holds for every renderer, including HEADLESS and jsdom tests (#7348). The full boot order is in game-setup-and-config.

Scene config

Pass it to super(), or as the Scene's entry in the game config.

constructor ()
{
    super({
        key: 'Level',
        active: false,              // true starts it at boot. The first Scene in the game config always starts
        physics: { arcade: { gravity: { y: 300 } } },   // turns on physics for this Scene, even with no game default
        loader: { path: 'assets/level/' },
        pack: { files: [ { type: 'image', key: 'bar', url: 'bar.png' } ] },
        plugins: [ 'Loader', 'TweenManager' ]           // only these Scene plugins. Leave out for all of them
    });
}
  • plugins lists the Scene plugins to install: 'Clock', 'DataManagerPlugin', 'InputPlugin', 'Loader', 'TweenManager', 'LightsPlugin', plus any from the game config. With [], this.time, this.data, this.input, this.load, this.tweens and this.lights are all undefined. this.add, this.cameras, this.events and this.scene are always there.
  • map replaces the whole injection map, so every property you leave out, such as this.add or this.cameras, is no longer set. mapAdd adds properties to the map, but can't rename ones it already has.
  • A Scene can be an object: { key: 'Menu', create () {}, update () {}, extend: { helper () {} } }. The functions in extend become Scene properties.
  • In TypeScript, this.scene.get<UI>('UI') returns the Scene typed as your class.

Moving between Scenes

Method What it does
start(key, data) Stops this Scene and starts key. With no key, restarts this Scene
restart(data) Stops this Scene and starts it again
launch(key, data) Starts key alongside this Scene
run(key, data) Wakes key if it's asleep, resumes it if it's paused, otherwise starts it
pause(key, data), resume(key, data) A paused Scene doesn't update, and takes no input, but it still renders
sleep(key, data), wake(key, data) A sleeping Scene doesn't update or render, and keeps its state
switch(key, data) Sleeps this Scene. Wakes key if it's asleep, otherwise starts it
stop(key, data) Shuts key down. Its Game Objects are destroyed
  • Each key defaults to this Scene. These methods are queued, and run at the start of the next game step, so the other Scene isn't running on the next line.
  • Starting a Scene which is already running, paused or asleep restarts it. That includes launch or run on a running Scene, and switch to a paused Scene. Check this.scene.isActive(key) first if the Scene may already be running.
  • These run at once: get, getStatus, isActive, isPaused, isSleeping, isVisible, setActive, setVisible and transition.
  • The render-order methods, and add and remove, run at once, or at the next step if called while the Scenes are updating: bringToTop, sendToBack, moveUp, moveDown, moveAbove(keyA, keyB), moveBelow(keyA, keyB), swapPosition.
  • this.scene.add(key, SceneClass, autoStart, data) adds a Scene at run time. remove(key) destroys it.

Passing data

  • start, restart, launch and run pass data to init(data) and create(data). this.sys.getData() returns it later.
  • restart() with no data, or start(key) with none, reuses the data from the last start. Pass {} to clear it.
  • Data given to pause, resume, sleep, wake, and to a switch or run which wakes or resumes a Scene, reaches only that event's listeners, as (sys, data). init and create don't run again.
create ()
{
    const onWake = (sys, data) =>
    {
        this.lives = data?.lives ?? this.lives;
    };

    this.events.on(Phaser.Scenes.Events.WAKE, onWake);

    //  this.events lives as long as the Scene, so remove the listener or it is added again on restart
    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
    {
        this.events.off(Phaser.Scenes.Events.WAKE, onWake);
    });
}
  • For state which many Scenes share, use this.registry (one for the game). this.data belongs to the Scene, and keeps its values across a restart until you call this.data.reset(). See data-manager.

Running Scenes together

  • Scenes render in the order of the game config's scene array, so later ones are drawn on top. The top Scene updates first, and gets input first.
  • A HUD is a second Scene, listed after the game Scene in the config (or moved with bringToTop), and launched by it. It has its own Camera, so it doesn't scroll or zoom with the game.
  • To pause the game under a menu: this.scene.pause() then this.scene.launch('Pause'). The paused Scene takes no input, so the Pause Scene must handle the resume: this.scene.resume('Level') then this.scene.stop().

One Scene listening to another must remove its listener when it shuts down, because the other Scene's emitter outlives it:

//  In the Level Scene, when a coin is collected
this.events.emit('score', 10);

//  In the HUD Scene
create ()
{
    const text = this.add.text(16, 16, 'Score: 0');
    const level = this.scene.get('Level');
    let score = 0;

    const onScore = (points) =>
    {
        score += points;
        text.setText(`Score: ${score}`);
    };

    level.events.on('score', onScore);

    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
    {
        level.events.off('score', onScore);
    });
}

The registry works the same way. Its change event for one key is Phaser.Data.Events.CHANGE_DATA_KEY + 'score', with (parent, value, previousValue), on this.registry.events. Remove it on SHUTDOWN too.

Cleaning up

A Scene instance is kept when it stops, and reused when it starts again. Shutdown destroys its Game Objects, tweens, timers, physics world, Key objects and this.input listeners. It doesn't remove:

  • listeners on this.events, the Scene's own emitter, which lives as long as the Scene. One added in create is added again on every restart;
  • listeners on anything global: this.registry, this.scale, this.game.events, this.sound, this.textures, or another Scene's events;
  • sounds made with this.sound.add, which belong to the game;
  • key captures, which are global. See input-keyboard-mouse-touch.

Remove these on SHUTDOWN, which runs on every stop and restart. DESTROY runs only when the Scene is removed from the game.

create ()
{
    const tick = (time, delta) => { /* every frame */ };

    this.events.on(Phaser.Scenes.Events.UPDATE, tick);

    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
    {
        this.events.off(Phaser.Scenes.Events.UPDATE, tick);
    });
}

Transitions

transition() runs both Scenes for duration ms, then stops (or sleeps) this one. It draws nothing itself: fade the Cameras yourself.

//  In the Scene going out
if (this.scene.transition({ target: 'Level2', duration: 500, data: { level: 2 } }))
{
    this.cameras.main.fadeOut(500);
}

//  In Level2's create
this.cameras.main.fadeIn(500);
  • It returns false, and does nothing, if the target doesn't exist, is already running, or either Scene is already transitioning.
  • Keys: target, duration (1000), sleep (false: stop this Scene at the end), remove, allowInput (false), moveAbove, moveBelow, data, onUpdate(progress), onStart.
  • Events: TRANSITION_OUT (targetScene, duration) on this Scene. On the target: TRANSITION_INIT (after init), then TRANSITION_START (after create) or TRANSITION_WAKE, each with (fromScene, duration), and TRANSITION_COMPLETE (fromScene) at the end.

Gotchas

  • Listeners on this.events added in create pile up across restarts, as do those on global emitters. Remove them on SHUTDOWN.
  • this.scene.start('X') stops the current Scene. Use launch to keep both.
  • launch, run or start on a running Scene restarts it.
  • Scene methods are queued until the next step.
  • Data given to wake or resume only reaches the event, not init or create.
  • restart() with no data reuses the old data.
  • Set up per-run state in init, not the constructor, which runs once.
  • this.physics and this.matter exist only if the game or the Scene config sets up that physics.
  • Never overwrite this.sys.