Loading...
Loading...
Compare original and translation side by side
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
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
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// 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);// 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);SceneManager.bootScene()SceneManager.create()scene.init(data)settings.dataSystems.start()startreadyscene.preload()scene.create(data)datascene.update(time, delta)shutdownPhaser.ScenesPhaser.Scenes.PENDINGPhaser.Scenes.RUNNINGinit()create()update()init()preload()create()update()SceneManager.bootScene()SceneManager.create()scene.init(data)settings.dataSystems.start()startreadyscene.preload()scene.create(data)datascene.update(time, delta)shutdownPhaser.ScenesPhaser.Scenes.PENDINGPhaser.Scenes.RUNNINGinit()create()update()init()preload()create()update()src/scene/InjectionMap.jssrc/scene/InjectionMap.js| 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 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物理系统(若已配置) |
// 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
}
};// 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
}
};SceneManagersrc/scene/SceneManager.jsthis.sceneSceneManagersrc/scene/SceneManager.jsthis.scene// 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
}
});// 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变化
}
});// 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');// 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');// 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// 方法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中的事件// 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// 暂停:停止更新循环,但仍渲染
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); // 显示// 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);
}// 动态添加新场景
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);
}// 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);
});
}
}// 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);
});
}
}super({ key: 'MinimalScene', plugins: [] });
// No this.load, this.tweens, this.time, this.input, this.data, this.lightssuper({ key: 'PreloadScene', plugins: ['Loader'] });
// Only this.load is available; this.tweens, this.time, etc. are undefinedsuper({ key: 'MinimalScene', plugins: [] });
// 无this.load, this.tweens, this.time, this.input, this.data, this.lightssuper({ key: 'PreloadScene', plugins: ['Loader'] });
// 仅this.load可用;this.tweens, this.time等未定义super()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()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' }
]
}
});
}
}init()init()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()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 = [];
});
}
}this.eventsthis.events.on('eventname', callback)this.eventsthis.events.on('eventname', callback)| 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 |
| 事件字符串 | 常量 | 回调签名 | 触发时机 |
|---|---|---|---|
| | | 场景首次实例化时触发一次(供插件使用) |
| | | 场景系统启动时触发(供插件使用) |
| | | 启动后触发,供用户代码使用 |
| | | |
| | | 每帧更新前触发 |
| | | 每帧更新期间触发 |
| | | 每帧更新后触发 |
| | | 场景渲染前触发 |
| | | 场景渲染后触发 |
| 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 |
| 事件字符串 | 常量 | 回调签名 | 触发时机 |
|---|---|---|---|
| | | 场景暂停时触发 |
| | | 场景恢复时触发 |
| | | 场景进入休眠时触发 |
| | | 场景被唤醒时触发 |
| | | 场景关闭时触发 |
| | | 场景被销毁时触发 |
| 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之后) |
| | | 目标场景(从休眠唤醒时) |
| | | 目标场景(过渡完成时) |
| Event String | Constant | Callback Signature |
|---|---|---|
| | |
| | |
| 事件字符串 | 常量 | 回调签名 |
|---|---|---|
| | |
| | |
this.scene.start('X')start()this.scene.start('X')launch()run()switch()start()switch()start()pause()sleep()this.systhis.systhis.scene.start()this.scene.restart()start()launch()init(data)create(data)settings.datathis.sys.getData()bringToTop()sendToBack()moveAbove()moveBelow()shutdowndestroy'shutdown''destroy'this.physicsthis.mattercreatecreate()init()init()shutdownthis.events.once('shutdown', ...)switch()run()this.scene.start('X')start()this.scene.start('X')launch()run()switch()start()switch()start()pause()sleep()this.systhis.systhis.scene.start()this.scene.restart()start()launch()init(data)create(data)settings.datathis.sys.getData()bringToTop()sendToBack()moveAbove()moveBelow()shutdowndestroy'shutdown''destroy'this.physicsthis.mattercreatecreate()init()init()shutdownthis.events.once('shutdown', ...)switch()run()