You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 07:52:03