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

Phaser 3玩家精灵与场景切换触发对象无交互问题求助

问题修复方案

你的代码里有几个关键问题导致场景切换没触发,逐个解决:

1. 场景配置与标识错误

  • 主配置文件里的scene选项必须是数组格式,你当前写法语法错误,要改成数组包裹场景类
  • 每个场景类的constructor里必须设置唯一key,否则scene.start()找不到目标场景

修改后的主配置:

var config = {
    type: Phaser.AUTO,
    width: 256,
    height: 224,
    backgroundColor: '#000000',
    pixelArt: true,
    input: {
      gamepad: true
    },
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 0 },
            debug: true
        }
    },
    scene: [TestRoom, TestRoom2] // 修正为数组格式
};

TestRoom的constructor修改:

constructor() {
    super({ key: 'TestRoom' }) // 添加场景唯一标识key
}

TestRoom2同理要添加key:

constructor() {
    super({ key: 'TestRoom2' })
}

2. 碰撞检测对象错误

你用自定义的this.player实例去做碰撞检测,但Phaser物理系统只能识别物理精灵对象,应该用Player类内部的sprite属性:this.player.sprite

3. 物理组未添加触发精灵

你创建了exitBox组,但没把定义好的exited精灵加入组,导致组内是空的,自然不会触发碰撞。要么把精灵加入组,要么直接用单个精灵做碰撞:

// 把exited精灵加入exitBox组
this.exitBox.add(this.exited);

如果只有一个出口,直接用单个精灵更简单:

this.physics.add.collider(this.player.sprite, this.exited, ...);

4. 回调函数this指向问题

普通函数作为碰撞回调时,内部的this不是当前场景,导致this.scene.start()无法执行。改成箭头函数就能保留场景的this指向:

this.physics.add.collider(this.player.sprite, this.exitBox, () => {
    this.scene.start('TestRoom2');
});

5. 移除Update里的重复碰撞器创建

你在update()里重复调用this.physics.collide(),会每帧创建新的碰撞器,完全没必要,直接删掉这行代码。


修改后的TestRoom.js关键代码片段

create()
{
    this.map = this.make.tilemap({ key: 'map' });
    this.map.landscape = this.map.addTilesetImage('house', 'tiles');
    this.map.createLayer("ground", [this.map.landscape], 0, 0);
    this.player = new Player(this, 128, 112);
    this.map.createLayer("above", [this.map.landscape], 0, 0);
    this.cameras.main.setSize(256,224);
    this.cameras.main.setBounds(0, 0, this.map.widthInPixels, this.map.heightInPixels);
    this.cameras.main.startFollow(this.player.sprite);
    this.cameras.main.setDeadzone(4,4);
    
    this.exited = this.physics.add.sprite(112, 220, 'exit').setOrigin(0,0);
    this.exitBox= this.physics.add.group();
    this.exitBox.add(this.exited); // 将精灵加入物理组
    
    // 正确配置碰撞检测与场景切换逻辑
    this.physics.add.collider(this.player.sprite, this.exitBox, () => {
        this.scene.start('TestRoom2');
    });
}

update() {
    this.player.update();
    // 移除重复的collide调用
}

这样修改后,玩家碰到出口精灵时就能正常触发场景切换了。

内容的提问来源于stack exchange,提问作者Kenzie Sanderson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:37:16