注册全局碰撞回调函数后通过otherCollider销毁节点时报错

  • Creator 版本: 3.3.2或3.6.1

  • 目标平台: chrome浏览器网页

  • 重现方式:

start() {
        if (PhysicsSystem2D.instance) {
            PhysicsSystem2D.instance.on(
                Contact2DType.BEGIN_CONTACT, this.onBeginContact, this
            );
        }
}
onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
    otherCollider.destroy();
    //或调用 otherCollider.node.destroy();
}
 

otherCollider内容:

  • 首个报错:
    为什么我全局监听碰撞后在onBeginContact回调里通过otherCollider参数调用otherCollider.destroy();直接报错:
    box2d.umd.js:7181 Uncaught Error
    at b2Body.SetActive (box2d.umd.js:7181:15)
    at b2RigidBody2D.setActive (rigid-body.ts:197:21)
    at b2RigidBody2D.onDisable (rigid-body.ts:58:14)
    at RigidBody2D.onDisable (rigid-body-2d.ts:512:24)
    at ComponentScheduler.disableComp (component-scheduler.ts:440:22)
    at NodeActivator._deactivateNodeRecursively (node-activator.ts:317:50)
    at NodeActivator.activateNode (node-activator.ts:187:18)
    at Node.set (base-node.ts:170:54)
    at Node.destroy (base-node.ts:1193:13)
    at Npc.onBeginContact (Npc.ts:159:28)

尝试了调用otherCollider.node.destroy();,但也报错:
Uncaught TypeError: Cannot read properties of null (reading ‘enabledContactListener’)
at PhysicsContact.emit (physics-contact.ts:244:20)
at PhysicsContactListener._onBeginContact [as _BeginContact] (physics-world.ts:366:11)
at PhysicsContactListener.BeginContact (physics-contact-listener.ts:67:18)
at b2PolygonAndCircleContact.Update (box2d.umd.js:11803:24)
at b2ContactManager.Collide (box2d.umd.js:12479:17)
at b2World.Step (box2d.umd.js:19588:33)
at b2PhysicsWorld.step (physics-world.ts:133:21)
at PhysicsSystem2D.postUpdate (physics-system.ts:246:31)
at Director.tick (director.ts:760:38)
at callback (game.ts:734:26)

  • 编辑器操作系统:win11 64位
  • 重现概率: 100%

搞个定时器,下一帧再释放嘛

1赞

我试了,确实有效,但这是为什么呢?

涨姿势了,感谢大佬的耐心解答。

你这叫回调自杀,回调还没有执行完,你就destroy了,他后续的清理工作没办法继续下去了

感谢!用计时器解决问题