Phaser 3中如何从物品栏场景切换回玩家来源的上一场景?
解决方案
1. 记录来源场景
在所有需要呼出物品栏的游戏场景中,监听触发物品栏的按键(比如ESC键),按下时先把当前场景的名称存到全局可访问的位置,再切换到物品栏场景:
// 示例:在某游戏场景的create方法中 create() { // 监听ESC键呼出物品栏 this.input.keyboard.on('keydown-ESC', () => { // 把当前场景名存在游戏实例的全局变量里 this.sys.game.previousScene = this.scene.key; // 切换到物品栏场景 this.scene.switch('InventoryScene'); }); // 其他场景逻辑代码... }
2. 物品栏场景返回来源场景
在物品栏场景的create方法中,监听同一按键,读取之前存储的场景名并切换回去:
// InventoryScene的create方法 create() { // 监听ESC键返回原场景 this.input.keyboard.on('keydown-ESC', () => { if (this.sys.game.previousScene) { this.scene.switch(this.sys.game.previousScene); } }); // 物品栏UI渲染、物品展示逻辑... }
3. 可选优化方案
- 不想用全局变量的话,可以用Phaser内置的
registry存储数据,它是专为跨场景共享数据设计的:// 存储场景名 this.registry.set('previousScene', this.scene.key); // 读取场景名 const prevSceneKey = this.registry.get('previousScene'); - 确保物品栏场景始终处于可用状态,可在游戏初始化时就启动并休眠它,避免重复创建:
// 游戏配置的scene数组中包含InventoryScene const gameConfig = { // 其他配置项... scene: [BootScene, Level1Scene, InventoryScene] }; // 或者在BootScene中启动并休眠物品栏场景 this.scene.launch('InventoryScene'); this.scene.sleep('InventoryScene');
内容的提问来源于stack exchange,提问作者EmptyStone
相关产品推荐
相关产品推荐

