scenes

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Scenes

场景

Scenes are the organizational backbone of a Phaser game. Each Scene has its own lifecycle (init, preload, create, update), its own set of injected systems (this.add, this.input, this.cameras, etc.), and can be started, stopped, paused, slept, or run in parallel with other Scenes. The ScenePlugin (
this.scene
) controls all multi-scene orchestration.
Key source paths:
src/scene/Scene.js
,
src/scene/Systems.js
,
src/scene/SceneManager.js
,
src/scene/ScenePlugin.js
,
src/scene/Settings.js
,
src/scene/const.js
,
src/scene/events/
,
src/scene/InjectionMap.js
Related skills: ../game-setup-and-config/SKILL.md, ../loading-assets/SKILL.md, ../events-system/SKILL.md
场景是Phaser游戏的组织核心。每个场景都有自己的生命周期(init、preload、create、update)、独立的注入系统(this.add、this.input、this.cameras等),并且可以启动、停止、暂停、休眠,或者与其他场景并行运行。ScenePlugin(
this.scene
)负责所有多场景的编排。
关键源码路径:
src/scene/Scene.js
,
src/scene/Systems.js
,
src/scene/SceneManager.js
,
src/scene/ScenePlugin.js
,
src/scene/Settings.js
,
src/scene/const.js
,
src/scene/events/
,
src/scene/InjectionMap.js
相关技能: ../game-setup-and-config/SKILL.md, ../loading-assets/SKILL.md, ../events-system/SKILL.md

Quick Start

快速入门

js
// Minimal scene with all lifecycle methods
class GameScene extends Phaser.Scene {
    constructor() {
        super('GameScene');
    }

    init(data) {
        // Called first. Receives data passed from other scenes.
        // 'data' is whatever was passed via scene.start('GameScene', { level: 1 })
        this.level = data.level || 1;
    }

    preload() {
        // Called after init. Load assets here.
        this.load.image('logo', 'assets/logo.png');
    }

    create(data) {
        // Called after preload completes. Set up game objects.
        // 'data' is the same object passed to init.
        this.add.image(400, 300, 'logo');
    }

    update(time, delta) {
        // Called every frame while scene is RUNNING.
        // time: current time (ms), delta: ms since last frame (smoothed)
    }
}

const config = {
    width: 800,
    height: 600,
    scene: [GameScene]
};

const game = new Phaser.Game(config);
js
// Minimal scene with all lifecycle methods
class GameScene extends Phaser.Scene {
    constructor() {
        super('GameScene');
    }

    init(data) {
        // Called first. Receives data passed from other scenes.
        // 'data' is whatever was passed via scene.start('GameScene', { level: 1 })
        this.level = data.level || 1;
    }

    preload() {
        // Called after init. Load assets here.
        this.load.image('logo', 'assets/logo.png');
    }

    create(data) {
        // Called after preload completes. Set up game objects.
        // 'data' is the same object passed to init.
        this.add.image(400, 300, 'logo');
    }

    update(time, delta) {
        // Called every frame while scene is RUNNING.
        // time: current time (ms), delta: ms since last frame (smoothed)
    }
}

const config = {
    width: 800,
    height: 600,
    scene: [GameScene]
};

const game = new Phaser.Game(config);

Core Concepts

核心概念

Scene Lifecycle

场景生命周期

The lifecycle is driven by
SceneManager.bootScene()
and
SceneManager.create()
:
  1. PENDING (0) - Scene is registered but not yet started.
  2. INIT (1) -
    scene.init(data)
    is called if defined. Data comes from
    settings.data
    .
  3. START (2) -
    Systems.start()
    fires. Events
    start
    and
    ready
    are emitted.
  4. LOADING (3) -
    scene.preload()
    is called if defined. Loader runs. On completion, proceeds to create.
  5. CREATING (4) -
    scene.create(data)
    is called if defined. Same
    data
    as init.
  6. RUNNING (5) -
    scene.update(time, delta)
    called every frame. Scene renders.
  7. PAUSED (6) - No update, but still renders.
  8. SLEEPING (7) - No update, no render. State preserved in memory.
  9. SHUTDOWN (8) - Scene is shut down, systems emit
    shutdown
    . Can be restarted.
  10. DESTROYED (9) - Scene is fully destroyed. Cannot be restarted.
State constants are on
Phaser.Scenes
:
Phaser.Scenes.PENDING
,
Phaser.Scenes.RUNNING
, etc.
Flow when no preload exists:
init()
->
create()
->
update()
loop (preload is skipped entirely).
Flow with preload:
init()
->
preload()
-> loader runs ->
create()
->
update()
loop.
生命周期由
SceneManager.bootScene()
SceneManager.create()
驱动:
  1. PENDING (0) - 场景已注册但尚未启动。
  2. INIT (1) - 如果定义了
    scene.init(data)
    则调用该方法。数据来自
    settings.data
  3. START (2) - 触发
    Systems.start()
    。发出
    start
    ready
    事件。
  4. LOADING (3) - 如果定义了
    scene.preload()
    则调用该方法。加载器运行。完成后进入创建阶段。
  5. CREATING (4) - 如果定义了
    scene.create(data)
    则调用该方法。使用与init相同的
    data
  6. RUNNING (5) - 场景运行时每帧调用
    scene.update(time, delta)
    。场景进行渲染。
  7. PAUSED (6) - 停止更新,但仍会渲染。
  8. SLEEPING (7) - 停止更新和渲染。状态保留在内存中。
  9. SHUTDOWN (8) - 场景关闭,系统发出
    shutdown
    事件。可重新启动。
  10. DESTROYED (9) - 场景被完全销毁。无法重新启动。
状态常量位于
Phaser.Scenes
Phaser.Scenes.PENDING
,
Phaser.Scenes.RUNNING
等。
无preload时的流程:
init()
->
create()
->
update()
循环(完全跳过preload)。
有preload时的流程:
init()
->
preload()
-> 加载器运行 ->
create()
->
update()
循环。

Scene-Injected Properties

场景注入属性

These properties are injected into every Scene instance via the InjectionMap (
src/scene/InjectionMap.js
). The left side is the Systems key, the right is the Scene property name.
这些属性通过InjectionMap(
src/scene/InjectionMap.js
)注入到每个场景实例中。左侧是系统键,右侧是场景属性名称。

Global Managers (shared across all scenes)

全局管理器(所有场景共享)

Scene PropertyTypeDescription
this.game
Phaser.Game
The Game instance
this.renderer
CanvasRenderer | WebGLRenderer
The active renderer
this.anims
Phaser.Animations.AnimationManager
Global animation manager
this.cache
Phaser.Cache.CacheManager
Global cache for non-image assets
this.plugins
Phaser.Plugins.PluginManager
Global plugin manager
this.registry
Phaser.Data.DataManager
Global data manager (shared between scenes)
this.scale
Phaser.Scale.ScaleManager
Global scale manager
this.sound
NoAudio | HTML5Audio | WebAudioSoundManager
Sound manager
this.textures
Phaser.Textures.TextureManager
Global texture manager
场景属性类型描述
this.game
Phaser.Game
游戏实例
this.renderer
CanvasRenderer | WebGLRenderer
当前激活的渲染器
this.anims
Phaser.Animations.AnimationManager
全局动画管理器
this.cache
Phaser.Cache.CacheManager
非图像资源的全局缓存
this.plugins
Phaser.Plugins.PluginManager
全局插件管理器
this.registry
Phaser.Data.DataManager
全局数据管理器(场景间共享)
this.scale
Phaser.Scale.ScaleManager
全局缩放管理器
this.sound
NoAudio | HTML5Audio | WebAudioSoundManager
声音管理器
this.textures
Phaser.Textures.TextureManager
全局纹理管理器

Scene-Specific Systems (unique per scene)

场景专属系统(每个场景独有)

Scene PropertyTypeDescription
this.sys
Phaser.Scenes.Systems
Scene systems (never overwrite)
this.events
Phaser.Events.EventEmitter
Scene-specific event emitter
this.cameras
Phaser.Cameras.Scene2D.CameraManager
Scene camera manager
this.add
Phaser.GameObjects.GameObjectFactory
Factory: creates and adds to display list
this.make
Phaser.GameObjects.GameObjectCreator
Creator: creates but does NOT add to display list
this.scene
Phaser.Scenes.ScenePlugin
Scene manager plugin (start/stop/launch)
this.children
Phaser.GameObjects.DisplayList
The scene display list
this.lights
Phaser.GameObjects.LightsManager
Scene lights (plugin)
this.data
Phaser.Data.DataManager
Scene-specific data manager
this.input
Phaser.Input.InputPlugin
Scene input manager (plugin)
this.load
Phaser.Loader.LoaderPlugin
Scene loader (plugin)
this.time
Phaser.Time.Clock
Scene time/clock (plugin)
this.tweens
Phaser.Tweens.TweenManager
Scene tween manager (plugin)
this.physics
Phaser.Physics.Arcade.ArcadePhysics
Arcade physics (if configured)
this.matter
Phaser.Physics.Matter.MatterPhysics
Matter physics (if configured)
场景属性类型描述
this.sys
Phaser.Scenes.Systems
场景系统(绝不能覆盖)
this.events
Phaser.Events.EventEmitter
场景专属事件发射器
this.cameras
Phaser.Cameras.Scene2D.CameraManager
场景相机管理器
this.add
Phaser.GameObjects.GameObjectFactory
工厂:创建并添加到显示列表
this.make
Phaser.GameObjects.GameObjectCreator
创建器:创建但不添加到显示列表
this.scene
Phaser.Scenes.ScenePlugin
场景管理器插件(启动/停止/启动并行场景)
this.children
Phaser.GameObjects.DisplayList
场景显示列表
this.lights
Phaser.GameObjects.LightsManager
场景灯光(插件)
this.data
Phaser.Data.DataManager
场景专属数据管理器
this.input
Phaser.Input.InputPlugin
场景输入管理器(插件)
this.load
Phaser.Loader.LoaderPlugin
场景加载器(插件)
this.time
Phaser.Time.Clock
场景时间/时钟(插件)
this.tweens
Phaser.Tweens.TweenManager
场景补间管理器(插件)
this.physics
Phaser.Physics.Arcade.ArcadePhysics
Arcade物理系统(若已配置)
this.matter
Phaser.Physics.Matter.MatterPhysics
Matter物理系统(若已配置)

Customizing the Injection Map

自定义注入映射

js
// Rename injected properties via scene config
const config = {
    key: 'MyScene',
    map: {
        add: 'makeStuff',   // this.makeStuff instead of this.add
        load: 'loader'      // this.loader instead of this.load
    }
};
js
// Rename injected properties via scene config
const config = {
    key: 'MyScene',
    map: {
        add: 'makeStuff',   // this.makeStuff instead of this.add
        load: 'loader'      // this.loader instead of this.load
    }
};

Scene Manager

场景管理器

The
SceneManager
(
src/scene/SceneManager.js
) is a game-level system. Do not call its methods directly -- use
this.scene
(the ScenePlugin) instead. The SceneManager:
  • Maintains an ordered array of scenes (determines render/update order)
  • Processes a queue of operations (start, stop, sleep, etc.) at the start of each game step
  • All ScenePlugin methods are queued, not immediate (they execute next frame)
SceneManager
src/scene/SceneManager.js
)是游戏级别的系统。请勿直接调用其方法——请使用
this.scene
(ScenePlugin)代替。SceneManager:
  • 维护场景的有序数组(决定渲染/更新顺序)
  • 在每个游戏步骤开始时处理操作队列(启动、停止、休眠等)
  • 所有ScenePlugin方法都是入队执行,而非立即执行(会在下一帧执行)

Common Patterns

常见模式

Switching Between Scenes

场景切换

js
// start() -- shuts down current scene, starts target scene
// Current scene gets SHUTDOWN event; target gets full lifecycle
this.scene.start('LevelTwo', { score: 100 });

// restart() -- shuts down and restarts the same scene
this.scene.restart({ score: 0 });

// switch() -- sleeps current scene, starts/wakes target scene
// Current scene state is preserved in memory
this.scene.switch('PauseMenu', { fromScene: 'GameScene' });

// transition() -- animated transition with duration
this.scene.transition({
    target: 'LevelTwo',
    duration: 1000,
    moveAbove: true,        // render target above this scene
    sleep: false,           // false = stop this scene (default), true = sleep it
    remove: false,          // true = remove this scene from manager after transition
    allowInput: false,      // allow input on this scene during transition
    data: { score: 100 },
    onUpdate: function (progress) {
        // progress: 0 to 1 over duration
    }
});
js
// start() -- 关闭当前场景,启动目标场景
// 当前场景收到SHUTDOWN事件;目标场景执行完整生命周期
this.scene.start('LevelTwo', { score: 100 });

// restart() -- 关闭并重启当前场景
this.scene.restart({ score: 0 });

// switch() -- 休眠当前场景,启动/唤醒目标场景
// 当前场景状态保留在内存中
this.scene.switch('PauseMenu', { fromScene: 'GameScene' });

// transition() -- 带时长的动画过渡
this.scene.transition({
    target: 'LevelTwo',
    duration: 1000,
    moveAbove: true,        // 将目标场景渲染在当前场景上方
    sleep: false,           // false = 停止当前场景(默认),true = 休眠当前场景
    remove: false,          // true = 过渡后将当前场景从管理器中移除
    allowInput: false,      // 过渡期间允许当前场景接收输入
    data: { score: 100 },
    onUpdate: function (progress) {
        // progress: 在时长内从0到1变化
    }
});

Running Scenes in Parallel

并行运行场景

js
// launch() -- starts another scene in parallel (does NOT stop current scene)
this.scene.launch('UIScene', { lives: 3 });

// run() -- smart launcher: starts if not running, resumes if paused, wakes if sleeping
this.scene.run('UIScene', { lives: 3 });

// Control render order of parallel scenes
this.scene.bringToTop('UIScene');      // render last (on top)
this.scene.sendToBack('Background');   // render first (behind)
this.scene.moveAbove('GameScene', 'UIScene');  // UIScene renders above GameScene
this.scene.moveBelow('GameScene', 'Background');
this.scene.moveUp('UIScene');          // move one position up
this.scene.moveDown('UIScene');        // move one position down
this.scene.swapPosition('SceneA', 'SceneB');
js
// launch() -- 并行启动另一个场景(不会停止当前场景)
this.scene.launch('UIScene', { lives: 3 });

// run() -- 智能启动器:未运行则启动,已暂停则恢复,已休眠则唤醒
this.scene.run('UIScene', { lives: 3 });

// 控制并行场景的渲染顺序
this.scene.bringToTop('UIScene');      // 最后渲染(在顶层)
this.scene.sendToBack('Background');   // 最先渲染(在底层)
this.scene.moveAbove('GameScene', 'UIScene');  // UIScene渲染在GameScene上方
this.scene.moveBelow('GameScene', 'Background');
this.scene.moveUp('UIScene');          // 向上移动一个位置
this.scene.moveDown('UIScene');        // 向下移动一个位置
this.scene.swapPosition('SceneA', 'SceneB');

Passing Data Between Scenes

场景间传递数据

js
// Method 1: Pass data via start/launch/restart/switch/wake/run
this.scene.start('LevelScene', { level: 5, score: 1200 });
// In LevelScene:
// init(data) { data.level === 5 }
// create(data) { data.score === 1200 }

// Method 2: Access data later via sys.getData()
// In receiving scene, at any time:
const data = this.sys.getData(); // returns settings.data

// Method 3: Global registry (shared across ALL scenes)
// In Scene A:
this.registry.set('playerHP', 100);
// In Scene B:
const hp = this.registry.get('playerHP'); // 100

// Method 4: Scene-specific data manager
this.data.set('localValue', 42);
this.data.get('localValue'); // 42

// Method 5: Direct scene reference
const otherScene = this.scene.get('OtherScene');
otherScene.somePublicProperty;

// Method 6: Events on the global registry
// In Scene A:
this.registry.events.on('changedata-playerHP', (parent, value, previousValue) => {
    // react to change
});
// In Scene B:
this.registry.set('playerHP', 50); // triggers the event in Scene A
js
// 方法1:通过start/launch/restart/switch/wake/run传递数据
this.scene.start('LevelScene', { level: 5, score: 1200 });
// 在LevelScene中:
// init(data) { data.level === 5 }
// create(data) { data.score === 1200 }

// 方法2:稍后通过sys.getData()访问数据
// 在接收场景的任何时间:
const data = this.sys.getData(); // 返回settings.data

// 方法3:全局注册表(所有场景共享)
// 在场景A中:
this.registry.set('playerHP', 100);
// 在场景B中:
const hp = this.registry.get('playerHP'); // 100

// 方法4:场景专属数据管理器
this.data.set('localValue', 42);
this.data.get('localValue'); // 42

// 方法5:直接引用场景
const otherScene = this.scene.get('OtherScene');
otherScene.somePublicProperty;

// 方法6:全局注册表上的事件
// 在场景A中:
this.registry.events.on('changedata-playerHP', (parent, value, previousValue) => {
    // 响应变化
});
// 在场景B中:
this.registry.set('playerHP', 50); // 触发场景A中的事件

Pausing and Resuming

暂停与恢复

js
// Pause: stops update loop, still renders
this.scene.pause();               // pause this scene
this.scene.pause('OtherScene');   // pause another scene

// Resume: restart update loop
this.scene.resume();
this.scene.resume('OtherScene', { message: 'welcome back' });

// Sleep: no update AND no render, but state preserved
this.scene.sleep();
this.scene.sleep('OtherScene');

// Wake: restore from sleep
this.scene.wake();
this.scene.wake('OtherScene', { data: 'here' });

// Stop: full shutdown, clears display list and timers
this.scene.stop();
this.scene.stop('OtherScene');

// Check state
this.scene.isActive('OtherScene');    // boolean
this.scene.isPaused('OtherScene');    // boolean
this.scene.isSleeping('OtherScene');  // boolean
this.scene.isVisible('OtherScene');   // boolean

// Control visibility/activity independently
this.scene.setActive(false);          // pause
this.scene.setActive(true);           // resume
this.scene.setVisible(false);         // hide but still update
this.scene.setVisible(true);          // show
js
// 暂停:停止更新循环,但仍渲染
this.scene.pause();               // 暂停当前场景
this.scene.pause('OtherScene');   // 暂停另一个场景

// 恢复:重启更新循环
this.scene.resume();
this.scene.resume('OtherScene', { message: 'welcome back' });

// 休眠:停止更新和渲染,但保留状态
this.scene.sleep();
this.scene.sleep('OtherScene');

// 唤醒:从休眠状态恢复
this.scene.wake();
this.scene.wake('OtherScene', { data: 'here' });

// 停止:完全关闭,清除显示列表和计时器
this.scene.stop();
this.scene.stop('OtherScene');

// 检查状态
this.scene.isActive('OtherScene');    // 布尔值
this.scene.isPaused('OtherScene');    // 布尔值
this.scene.isSleeping('OtherScene');  // 布尔值
this.scene.isVisible('OtherScene');   // 布尔值

// 独立控制可见性/活跃状态
this.scene.setActive(false);          // 暂停
this.scene.setActive(true);           // 恢复
this.scene.setVisible(false);         // 隐藏但仍更新
this.scene.setVisible(true);          // 显示

Adding and Removing Scenes at Runtime

运行时添加和移除场景

js
// Add a new scene dynamically
this.scene.add('BonusLevel', BonusLevelScene, false, { someData: true });
// args: key, sceneConfig, autoStart, data

// Remove a scene entirely (destroyed, cannot be restarted)
this.scene.remove('BonusLevel');

// Spawn multiple instances from one class
for (let i = 0; i < 5; i++) {
    this.scene.add('Level' + i, new LevelScene('Level' + i), false);
}
js
// 动态添加新场景
this.scene.add('BonusLevel', BonusLevelScene, false, { someData: true });
// 参数:键、场景配置、自动启动、数据

// 完全移除场景(已销毁,无法重启)
this.scene.remove('BonusLevel');

// 从一个类生成多个实例
for (let i = 0; i < 5; i++) {
    this.scene.add('Level' + i, new LevelScene('Level' + i), false);
}

Cross-Scene Event Communication

跨场景事件通信

One scene emits custom events; another listens. The emitting scene is decoupled.
js
// GameScene emits events
class GameScene extends Phaser.Scene {
    collectCoin(coin) {
        coin.destroy();
        this.events.emit('addScore', 10);
    }
}

// UIScene listens (launched in parallel with { active: true })
class UIScene extends Phaser.Scene {
    constructor() {
        super({ key: 'UIScene', active: true });
    }

    create() {
        this.score = 0;
        this.scoreText = this.add.text(10, 10, 'Score: 0');

        // Listen for events from GameScene
        const gameScene = this.scene.get('GameScene');
        gameScene.events.on('addScore', (points) => {
            this.score += points;
            this.scoreText.setText('Score: ' + this.score);
        });
    }
}
一个场景触发自定义事件;另一个场景监听。触发场景与监听场景解耦。
js
// GameScene触发事件
class GameScene extends Phaser.Scene {
    collectCoin(coin) {
        coin.destroy();
        this.events.emit('addScore', 10);
    }
}

// UIScene监听(并行启动,{ active: true })
class UIScene extends Phaser.Scene {
    constructor() {
        super({ key: 'UIScene', active: true });
    }

    create() {
        this.score = 0;
        this.scoreText = this.add.text(10, 10, 'Score: 0');

        // 监听GameScene的事件
        const gameScene = this.scene.get('GameScene');
        gameScene.events.on('addScore', (points) => {
            this.score += points;
            this.scoreText.setText('Score: ' + this.score);
        });
    }
}

Configuring Plugins Per Scene

按场景配置插件

Disable all default plugins (only core plugins remain):
js
super({ key: 'MinimalScene', plugins: [] });
// No this.load, this.tweens, this.time, this.input, this.data, this.lights
Include only specific plugins:
js
super({ key: 'PreloadScene', plugins: ['Loader'] });
// Only this.load is available; this.tweens, this.time, etc. are undefined
禁用所有默认插件(仅保留核心插件):
js
super({ key: 'MinimalScene', plugins: [] });
// 无this.load, this.tweens, this.time, this.input, this.data, this.lights
仅包含特定插件:
js
super({ key: 'PreloadScene', plugins: ['Loader'] });
// 仅this.load可用;this.tweens, this.time等未定义

Scene Config in Constructor

构造函数中的场景配置

Pass config to
super()
for per-scene physics, loader, or preloaded files:
js
class Level1 extends Phaser.Scene {
    constructor() {
        super({
            key: 'Level1',
            physics: { arcade: { debug: true, gravity: { y: 200 } } },
            loader: { path: 'assets/levels/1/' },
            // 'pack' loads files before preload() runs -- good for progress bar assets
            pack: {
                files: [
                    { type: 'image', key: 'bar', url: 'loaderBar.png' }
                ]
            }
        });
    }
}
super()
传递配置,实现按场景配置物理系统、加载器或预加载文件:
js
class Level1 extends Phaser.Scene {
    constructor() {
        super({
            key: 'Level1',
            physics: { arcade: { debug: true, gravity: { y: 200 } } },
            loader: { path: 'assets/levels/1/' },
            // 'pack'在preload()运行前加载文件——适合进度条资源
            pack: {
                files: [
                    { type: 'image', key: 'bar', url: 'loaderBar.png' }
                ]
            }
        });
    }
}

Safely Restarting Scenes

安全重启场景

Reset state in
init()
, not the constructor. The constructor runs once;
init()
runs every start.
js
class GameScene extends Phaser.Scene {
    constructor() {
        super('GameScene');
        // BAD: this.gameOver = false; -- only set once, not on restart
    }

    init() {
        // GOOD: reset state every time the scene starts
        this.gameOver = false;
        this.score = 0;
    }

    create() {
        // Clean up on shutdown to avoid stale references
        this.events.once('shutdown', () => {
            // Clear any arrays holding game object references
            this.enemies = [];
        });
    }
}
init()
中重置状态,而非构造函数。构造函数仅运行一次;
init()
每次启动时都会运行。
js
class GameScene extends Phaser.Scene {
    constructor() {
        super('GameScene');
        // 错误:this.gameOver = false; -- 仅设置一次,重启时不会重置
    }

    init() {
        // 正确:每次场景启动时重置状态
        this.gameOver = false;
        this.score = 0;
    }

    create() {
        // 关闭时清理,避免无效引用
        this.events.once('shutdown', () => {
            // 清空所有持有游戏对象引用的数组
            this.enemies = [];
        });
    }
}

Events

事件

All events are emitted on
this.events
(the scene-specific EventEmitter) and have string values. Listen via
this.events.on('eventname', callback)
.
所有事件都在
this.events
(场景专属EventEmitter)上触发,且为字符串值。通过
this.events.on('eventname', callback)
监听。

Lifecycle Events

生命周期事件

Event StringConstantCallback SignatureWhen
'boot'
Phaser.Scenes.Events.BOOT
(sys)
Once, when scene is first instantiated (for plugins)
'start'
Phaser.Scenes.Events.START
(sys)
Scene systems start (for plugins)
'ready'
Phaser.Scenes.Events.READY
(sys, data)
After start, for user code
'create'
Phaser.Scenes.Events.CREATE
(scene)
After
create()
method runs, scene is now RUNNING
'preupdate'
Phaser.Scenes.Events.PRE_UPDATE
(time, delta)
Before update each frame
'update'
Phaser.Scenes.Events.UPDATE
(time, delta)
During update each frame
'postupdate'
Phaser.Scenes.Events.POST_UPDATE
(time, delta)
After update each frame
'prerender'
Phaser.Scenes.Events.PRE_RENDER
(renderer)
Before scene renders
'render'
Phaser.Scenes.Events.RENDER
(renderer)
After scene renders
事件字符串常量回调签名触发时机
'boot'
Phaser.Scenes.Events.BOOT
(sys)
场景首次实例化时触发一次(供插件使用)
'start'
Phaser.Scenes.Events.START
(sys)
场景系统启动时触发(供插件使用)
'ready'
Phaser.Scenes.Events.READY
(sys, data)
启动后触发,供用户代码使用
'create'
Phaser.Scenes.Events.CREATE
(scene)
create()
方法运行后触发,场景进入RUNNING状态
'preupdate'
Phaser.Scenes.Events.PRE_UPDATE
(time, delta)
每帧更新前触发
'update'
Phaser.Scenes.Events.UPDATE
(time, delta)
每帧更新期间触发
'postupdate'
Phaser.Scenes.Events.POST_UPDATE
(time, delta)
每帧更新后触发
'prerender'
Phaser.Scenes.Events.PRE_RENDER
(renderer)
场景渲染前触发
'render'
Phaser.Scenes.Events.RENDER
(renderer)
场景渲染后触发

State-Change Events

状态变化事件

Event StringConstantCallback SignatureWhen
'pause'
Phaser.Scenes.Events.PAUSE
(sys, data)
Scene is paused
'resume'
Phaser.Scenes.Events.RESUME
(sys, data)
Scene is resumed
'sleep'
Phaser.Scenes.Events.SLEEP
(sys, data)
Scene is sent to sleep
'wake'
Phaser.Scenes.Events.WAKE
(sys, data)
Scene is woken up
'shutdown'
Phaser.Scenes.Events.SHUTDOWN
(sys, data)
Scene is shutting down
'destroy'
Phaser.Scenes.Events.DESTROY
(sys)
Scene is being destroyed
事件字符串常量回调签名触发时机
'pause'
Phaser.Scenes.Events.PAUSE
(sys, data)
场景暂停时触发
'resume'
Phaser.Scenes.Events.RESUME
(sys, data)
场景恢复时触发
'sleep'
Phaser.Scenes.Events.SLEEP
(sys, data)
场景进入休眠时触发
'wake'
Phaser.Scenes.Events.WAKE
(sys, data)
场景被唤醒时触发
'shutdown'
Phaser.Scenes.Events.SHUTDOWN
(sys, data)
场景关闭时触发
'destroy'
Phaser.Scenes.Events.DESTROY
(sys)
场景被销毁时触发

Transition Events

过渡事件

Event StringConstantCallback SignatureEmitted On
'transitionout'
TRANSITION_OUT
(targetScene, duration)
Source scene
'transitioninit'
TRANSITION_INIT
(fromScene, duration)
Target scene (during init)
'transitionstart'
TRANSITION_START
(fromScene, duration)
Target scene (after create)
'transitionwake'
TRANSITION_WAKE
(fromScene, duration)
Target scene (if woken from sleep)
'transitioncomplete'
TRANSITION_COMPLETE
(scene)
Target scene (when done)
事件字符串常量回调签名触发场景
'transitionout'
TRANSITION_OUT
(targetScene, duration)
源场景
'transitioninit'
TRANSITION_INIT
(fromScene, duration)
目标场景(初始化期间)
'transitionstart'
TRANSITION_START
(fromScene, duration)
目标场景(create之后)
'transitionwake'
TRANSITION_WAKE
(fromScene, duration)
目标场景(从休眠唤醒时)
'transitioncomplete'
TRANSITION_COMPLETE
(scene)
目标场景(过渡完成时)

Game Object Events

游戏对象事件

Event StringConstantCallback Signature
'addedtoscene'
ADDED_TO_SCENE
(gameObject, scene)
'removedfromscene'
REMOVED_FROM_SCENE
(gameObject, scene)
For detailed API reference tables and source file maps, see the reference guide.
事件字符串常量回调签名
'addedtoscene'
ADDED_TO_SCENE
(gameObject, scene)
'removedfromscene'
REMOVED_FROM_SCENE
(gameObject, scene)
如需详细的API参考表和源码文件映射,请查看参考指南

Gotchas and Common Mistakes

注意事项与常见错误

  1. Operations are queued, not immediate. Calling
    this.scene.start('X')
    does not start X synchronously. It happens at the next SceneManager update. Do not rely on the target scene's state within the same frame.
  2. start()
    shuts down the calling scene.
    this.scene.start('X')
    stops the current scene and starts X. If you want both running, use
    launch()
    or
    run()
    .
  3. switch()
    sleeps,
    start()
    shuts down.
    switch()
    preserves the current scene in memory (sleep), while
    start()
    triggers a full shutdown. Sleeping scenes still have their events and references live.
  4. Paused scenes still render.
    pause()
    only stops the update loop. The scene is still drawn. Use
    sleep()
    to stop both update and render.
  5. Do not overwrite
    this.sys
    .
    The Scene class JSDoc explicitly warns: overwriting
    this.sys
    will break everything.
  6. this.scene.start()
    with no key restarts the current scene.
    This is equivalent to
    this.scene.restart()
    .
  7. Data passed to
    start()
    /
    launch()
    is available in both
    init(data)
    and
    create(data)
    .
    It is stored in
    settings.data
    and accessible later via
    this.sys.getData()
    .
  8. Sleeping scenes can still receive events from other scenes. If Scene A is sleeping but Scene B emits on the global registry, Scene A's listeners still fire. Be careful with active listeners on sleeping scenes.
  9. Scene render order = array order. Scenes later in the array render on top. Use
    bringToTop()
    ,
    sendToBack()
    ,
    moveAbove()
    ,
    moveBelow()
    to control layering.
  10. shutdown
    vs
    destroy
    .
    Shutdown puts a scene into hibernation (can restart). Destroy permanently removes it. Listen to
    'shutdown'
    to free resources that should be recreated on restart. Listen to
    'destroy'
    for final cleanup.
  11. Plugin properties like
    this.physics
    and
    this.matter
    are only available if the physics system is configured.
    They will be undefined otherwise.
  12. The
    create
    event fires AFTER the
    create()
    method returns
    , and after the status changes to RUNNING. If you need to do post-create setup, listen for this event.
  13. Reset state in
    init()
    , not the constructor.
    The constructor only runs once when the scene is first instantiated.
    init()
    runs every time the scene starts/restarts. Place state resets there.
  14. Clean up on
    shutdown
    to avoid stale references.
    Listen for
    this.events.once('shutdown', ...)
    to clear arrays holding game objects, remove external event listeners, etc. Stale references to destroyed game objects cause errors on restart.
  15. switch()
    restarts a paused scene, never resumes it.
    If you need resume behavior, use
    run()
    instead.
  16. Scenes update in reverse order, render in forward order. The top scene updates first (gets input priority), but renders last (appears on top). Establish render order in the game config scene array.
  1. 操作是入队执行,而非立即生效。 调用
    this.scene.start('X')
    不会同步启动X。会在下一次SceneManager更新时执行。不要在同一帧内依赖目标场景的状态。
  2. start()
    会关闭调用场景。
    this.scene.start('X')
    会停止当前场景并启动X。如果希望两个场景同时运行,请使用
    launch()
    run()
  3. switch()
    是休眠,
    start()
    是关闭。
    switch()
    会将当前场景状态保留在内存中(休眠),而
    start()
    会触发完全关闭。休眠场景的事件和引用仍然有效。
  4. 暂停的场景仍会渲染。
    pause()
    仅停止更新循环。场景仍会被绘制。如需停止更新和渲染,请使用
    sleep()
  5. 不要覆盖
    this.sys
    Scene类的JSDoc明确警告:覆盖
    this.sys
    会破坏所有功能。
  6. 不带键的
    this.scene.start()
    会重启当前场景。
    这等同于
    this.scene.restart()
  7. 传递给
    start()
    /
    launch()
    的数据在
    init(data)
    create(data)
    中都可用。
    数据存储在
    settings.data
    中,之后可通过
    this.sys.getData()
    访问。
  8. 休眠场景仍能接收其他场景的事件。 如果场景A处于休眠状态,但场景B在全局注册表上触发事件,场景A的监听器仍会执行。需注意休眠场景上的活跃监听器。
  9. 场景渲染顺序 = 数组顺序。 数组中靠后的场景渲染在顶层。使用
    bringToTop()
    ,
    sendToBack()
    ,
    moveAbove()
    ,
    moveBelow()
    控制层级。
  10. shutdown
    destroy
    的区别。
    Shutdown将场景置于休眠状态(可重启)。Destroy会永久移除场景。监听
    'shutdown'
    以释放需要在重启时重新创建的资源。监听
    'destroy'
    以进行最终清理。
  11. 插件属性如
    this.physics
    this.matter
    仅在物理系统已配置时可用。
    否则它们会是未定义的。
  12. create
    事件在
    create()
    方法返回后触发
    ,且在状态变为RUNNING之后。如需进行创建后的设置,请监听此事件。
  13. init()
    中重置状态,而非构造函数。
    构造函数仅在场景首次实例化时运行一次。
    init()
    每次场景启动/重启时都会运行。将状态重置放在此处。
  14. shutdown
    时清理以避免无效引用。
    监听
    this.events.once('shutdown', ...)
    以清空持有游戏对象的数组、移除外部事件监听器等。已销毁游戏对象的无效引用会导致重启时出错。
  15. switch()
    会重启暂停的场景,不会恢复。
    如需恢复行为,请使用
    run()
    代替。
  16. 场景更新顺序与渲染顺序相反。 顶层场景先更新(获得输入优先级),但最后渲染(显示在顶层)。在游戏配置的场景数组中设置渲染顺序。