scenes
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseScenes
场景
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 () controls all multi-scene orchestration.this.scene
Key source paths: , , , , , , ,
Related skills: ../game-setup-and-config/SKILL.md, ../loading-assets/SKILL.md, ../events-system/SKILL.md
src/scene/Scene.jssrc/scene/Systems.jssrc/scene/SceneManager.jssrc/scene/ScenePlugin.jssrc/scene/Settings.jssrc/scene/const.jssrc/scene/events/src/scene/InjectionMap.js场景是Phaser游戏的组织核心。每个场景都有自己的生命周期(init、preload、create、update)、独立的注入系统(this.add、this.input、this.cameras等),并且可以启动、停止、暂停、休眠,或者与其他场景并行运行。ScenePlugin()负责所有多场景的编排。this.scene
关键源码路径: , , , , , , ,
相关技能: ../game-setup-and-config/SKILL.md, ../loading-assets/SKILL.md, ../events-system/SKILL.md
src/scene/Scene.jssrc/scene/Systems.jssrc/scene/SceneManager.jssrc/scene/ScenePlugin.jssrc/scene/Settings.jssrc/scene/const.jssrc/scene/events/src/scene/InjectionMap.jsQuick 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 and :
SceneManager.bootScene()SceneManager.create()- PENDING (0) - Scene is registered but not yet started.
- INIT (1) - is called if defined. Data comes from
scene.init(data).settings.data - START (2) - fires. Events
Systems.start()andstartare emitted.ready - LOADING (3) - is called if defined. Loader runs. On completion, proceeds to create.
scene.preload() - CREATING (4) - is called if defined. Same
scene.create(data)as init.data - RUNNING (5) - called every frame. Scene renders.
scene.update(time, delta) - PAUSED (6) - No update, but still renders.
- SLEEPING (7) - No update, no render. State preserved in memory.
- SHUTDOWN (8) - Scene is shut down, systems emit . Can be restarted.
shutdown - DESTROYED (9) - Scene is fully destroyed. Cannot be restarted.
State constants are on : , , etc.
Phaser.ScenesPhaser.Scenes.PENDINGPhaser.Scenes.RUNNINGFlow when no preload exists: -> -> loop (preload is skipped entirely).
init()create()update()Flow with preload: -> -> loader runs -> -> loop.
init()preload()create()update()生命周期由和驱动:
SceneManager.bootScene()SceneManager.create()- PENDING (0) - 场景已注册但尚未启动。
- INIT (1) - 如果定义了则调用该方法。数据来自
scene.init(data)。settings.data - START (2) - 触发。发出
Systems.start()和start事件。ready - LOADING (3) - 如果定义了则调用该方法。加载器运行。完成后进入创建阶段。
scene.preload() - CREATING (4) - 如果定义了则调用该方法。使用与init相同的
scene.create(data)。data - RUNNING (5) - 场景运行时每帧调用。场景进行渲染。
scene.update(time, delta) - PAUSED (6) - 停止更新,但仍会渲染。
- SLEEPING (7) - 停止更新和渲染。状态保留在内存中。
- SHUTDOWN (8) - 场景关闭,系统发出事件。可重新启动。
shutdown - DESTROYED (9) - 场景被完全销毁。无法重新启动。
状态常量位于:, 等。
Phaser.ScenesPhaser.Scenes.PENDINGPhaser.Scenes.RUNNING无preload时的流程: -> -> 循环(完全跳过preload)。
init()create()update()有preload时的流程: -> -> 加载器运行 -> -> 循环。
init()preload()create()update()Scene-Injected Properties
场景注入属性
These properties are injected into every Scene instance via the InjectionMap (). The left side is the Systems key, the right is the Scene property name.
src/scene/InjectionMap.js这些属性通过InjectionMap()注入到每个场景实例中。左侧是系统键,右侧是场景属性名称。
src/scene/InjectionMap.jsGlobal Managers (shared across all scenes)
全局管理器(所有场景共享)
| Scene Property | Type | Description |
|---|---|---|
| | The Game instance |
| | The active renderer |
| | Global animation manager |
| | Global cache for non-image assets |
| | Global plugin manager |
| | Global data manager (shared between scenes) |
| | Global scale manager |
| | Sound manager |
| | Global texture manager |
| 场景属性 | 类型 | 描述 |
|---|---|---|
| | 游戏实例 |
| | 当前激活的渲染器 |
| | 全局动画管理器 |
| | 非图像资源的全局缓存 |
| | 全局插件管理器 |
| | 全局数据管理器(场景间共享) |
| | 全局缩放管理器 |
| | 声音管理器 |
| | 全局纹理管理器 |
Scene-Specific Systems (unique per scene)
场景专属系统(每个场景独有)
| Scene Property | Type | Description |
|---|---|---|
| | Scene systems (never overwrite) |
| | Scene-specific event emitter |
| | Scene camera manager |
| | Factory: creates and adds to display list |
| | Creator: creates but does NOT add to display list |
| | Scene manager plugin (start/stop/launch) |
| | The scene display list |
| | Scene lights (plugin) |
| | Scene-specific data manager |
| | Scene input manager (plugin) |
| | Scene loader (plugin) |
| | Scene time/clock (plugin) |
| | Scene tween manager (plugin) |
| | Arcade physics (if configured) |
| | Matter physics (if configured) |
| 场景属性 | 类型 | 描述 |
|---|---|---|
| | 场景系统(绝不能覆盖) |
| | 场景专属事件发射器 |
| | 场景相机管理器 |
| | 工厂:创建并添加到显示列表 |
| | 创建器:创建但不添加到显示列表 |
| | 场景管理器插件(启动/停止/启动并行场景) |
| | 场景显示列表 |
| | 场景灯光(插件) |
| | 场景专属数据管理器 |
| | 场景输入管理器(插件) |
| | 场景加载器(插件) |
| | 场景时间/时钟(插件) |
| | 场景补间管理器(插件) |
| | Arcade物理系统(若已配置) |
| | 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 () is a game-level system. Do not call its methods directly -- use (the ScenePlugin) instead. The SceneManager:
SceneManagersrc/scene/SceneManager.jsthis.scene- 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)
SceneManagersrc/scene/SceneManager.jsthis.scene- 维护场景的有序数组(决定渲染/更新顺序)
- 在每个游戏步骤开始时处理操作队列(启动、停止、休眠等)
- 所有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 Ajs
// 方法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); // showjs
// 暂停:停止更新循环,但仍渲染
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.lightsInclude 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 for per-scene physics, loader, or preloaded files:
super()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 , not the constructor. The constructor runs once; runs every start.
init()init()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 (the scene-specific EventEmitter) and have string values. Listen via .
this.eventsthis.events.on('eventname', callback)所有事件都在(场景专属EventEmitter)上触发,且为字符串值。通过监听。
this.eventsthis.events.on('eventname', callback)Lifecycle Events
生命周期事件
| Event String | Constant | Callback Signature | When |
|---|---|---|---|
| | | Once, when scene is first instantiated (for plugins) |
| | | Scene systems start (for plugins) |
| | | After start, for user code |
| | | After |
| | | Before update each frame |
| | | During update each frame |
| | | After update each frame |
| | | Before scene renders |
| | | After scene renders |
| 事件字符串 | 常量 | 回调签名 | 触发时机 |
|---|---|---|---|
| | | 场景首次实例化时触发一次(供插件使用) |
| | | 场景系统启动时触发(供插件使用) |
| | | 启动后触发,供用户代码使用 |
| | | |
| | | 每帧更新前触发 |
| | | 每帧更新期间触发 |
| | | 每帧更新后触发 |
| | | 场景渲染前触发 |
| | | 场景渲染后触发 |
State-Change Events
状态变化事件
| Event String | Constant | Callback Signature | When |
|---|---|---|---|
| | | Scene is paused |
| | | Scene is resumed |
| | | Scene is sent to sleep |
| | | Scene is woken up |
| | | Scene is shutting down |
| | | Scene is being destroyed |
| 事件字符串 | 常量 | 回调签名 | 触发时机 |
|---|---|---|---|
| | | 场景暂停时触发 |
| | | 场景恢复时触发 |
| | | 场景进入休眠时触发 |
| | | 场景被唤醒时触发 |
| | | 场景关闭时触发 |
| | | 场景被销毁时触发 |
Transition Events
过渡事件
| Event String | Constant | Callback Signature | Emitted On |
|---|---|---|---|
| | | Source scene |
| | | Target scene (during init) |
| | | Target scene (after create) |
| | | Target scene (if woken from sleep) |
| | | Target scene (when done) |
| 事件字符串 | 常量 | 回调签名 | 触发场景 |
|---|---|---|---|
| | | 源场景 |
| | | 目标场景(初始化期间) |
| | | 目标场景(create之后) |
| | | 目标场景(从休眠唤醒时) |
| | | 目标场景(过渡完成时) |
Game Object Events
游戏对象事件
| Event String | Constant | Callback Signature |
|---|---|---|
| | |
| | |
For detailed API reference tables and source file maps, see the reference guide.
| 事件字符串 | 常量 | 回调签名 |
|---|---|---|
| | |
| | |
如需详细的API参考表和源码文件映射,请查看参考指南。
Gotchas and Common Mistakes
注意事项与常见错误
-
Operations are queued, not immediate. Callingdoes not start X synchronously. It happens at the next SceneManager update. Do not rely on the target scene's state within the same frame.
this.scene.start('X') -
shuts down the calling scene.
start()stops the current scene and starts X. If you want both running, usethis.scene.start('X')orlaunch().run() -
sleeps,
switch()shuts down.start()preserves the current scene in memory (sleep), whileswitch()triggers a full shutdown. Sleeping scenes still have their events and references live.start() -
Paused scenes still render.only stops the update loop. The scene is still drawn. Use
pause()to stop both update and render.sleep() -
Do not overwrite. The Scene class JSDoc explicitly warns: overwriting
this.syswill break everything.this.sys -
with no key restarts the current scene. This is equivalent to
this.scene.start().this.scene.restart() -
Data passed to/
start()is available in bothlaunch()andinit(data). It is stored increate(data)and accessible later viasettings.data.this.sys.getData() -
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.
-
Scene render order = array order. Scenes later in the array render on top. Use,
bringToTop(),sendToBack(),moveAbove()to control layering.moveBelow() -
vs
shutdown. Shutdown puts a scene into hibernation (can restart). Destroy permanently removes it. Listen todestroyto free resources that should be recreated on restart. Listen to'shutdown'for final cleanup.'destroy' -
Plugin properties likeand
this.physicsare only available if the physics system is configured. They will be undefined otherwise.this.matter -
Theevent fires AFTER the
createmethod returns, and after the status changes to RUNNING. If you need to do post-create setup, listen for this event.create() -
Reset state in, 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.init() -
Clean up onto avoid stale references. Listen for
shutdownto clear arrays holding game objects, remove external event listeners, etc. Stale references to destroyed game objects cause errors on restart.this.events.once('shutdown', ...) -
restarts a paused scene, never resumes it. If you need resume behavior, use
switch()instead.run() -
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.
-
操作是入队执行,而非立即生效。 调用不会同步启动X。会在下一次SceneManager更新时执行。不要在同一帧内依赖目标场景的状态。
this.scene.start('X') -
会关闭调用场景。
start()会停止当前场景并启动X。如果希望两个场景同时运行,请使用this.scene.start('X')或launch()。run() -
是休眠,
switch()是关闭。start()会将当前场景状态保留在内存中(休眠),而switch()会触发完全关闭。休眠场景的事件和引用仍然有效。start() -
暂停的场景仍会渲染。仅停止更新循环。场景仍会被绘制。如需停止更新和渲染,请使用
pause()。sleep() -
不要覆盖。 Scene类的JSDoc明确警告:覆盖
this.sys会破坏所有功能。this.sys -
不带键的会重启当前场景。 这等同于
this.scene.start()。this.scene.restart() -
传递给/
start()的数据在launch()和init(data)中都可用。 数据存储在create(data)中,之后可通过settings.data访问。this.sys.getData() -
休眠场景仍能接收其他场景的事件。 如果场景A处于休眠状态,但场景B在全局注册表上触发事件,场景A的监听器仍会执行。需注意休眠场景上的活跃监听器。
-
场景渲染顺序 = 数组顺序。 数组中靠后的场景渲染在顶层。使用,
bringToTop(),sendToBack(),moveAbove()控制层级。moveBelow() -
与
shutdown的区别。 Shutdown将场景置于休眠状态(可重启)。Destroy会永久移除场景。监听destroy以释放需要在重启时重新创建的资源。监听'shutdown'以进行最终清理。'destroy' -
插件属性如和
this.physics仅在物理系统已配置时可用。 否则它们会是未定义的。this.matter -
事件在
create方法返回后触发,且在状态变为RUNNING之后。如需进行创建后的设置,请监听此事件。create() -
在中重置状态,而非构造函数。 构造函数仅在场景首次实例化时运行一次。
init()每次场景启动/重启时都会运行。将状态重置放在此处。init() -
在时清理以避免无效引用。 监听
shutdown以清空持有游戏对象的数组、移除外部事件监听器等。已销毁游戏对象的无效引用会导致重启时出错。this.events.once('shutdown', ...) -
会重启暂停的场景,不会恢复。 如需恢复行为,请使用
switch()代替。run() -
场景更新顺序与渲染顺序相反。 顶层场景先更新(获得输入优先级),但最后渲染(显示在顶层)。在游戏配置的场景数组中设置渲染顺序。