如何在碰撞后删除Box2dWeb中的主体

Bou*_*ess 5 javascript box2dweb

在Update函数内部,如果2个实体发生碰撞,我想删除它们(或将它们标记为需要删除,并在时间步骤结束时删除它们).我怎么做到这一点?

在更新功能中我尝试

var bodyA = this.m_fixtureA.m_body;
...
bodyA.m_world.DestroyBody(bodyA);
Run Code Online (Sandbox Code Playgroud)

但是,它们不会被删除.似乎当我尝试删除它们时,this.IsLocked()设置为true.

for*_*net 9

如果world.IsLocked()函数返回true,则世界不会删除实体.并且world.IsLocked()将在世界迈出一步时返回true.在步骤中移除主体可能会导致问题,因此在碰撞后销毁主体的正确方法是将它们注册到变量中,然后在步骤完成后销毁它们.

//Pseudo code:
var destroy_list = [];

// Your contact listener
var listener = function () {
  // Push the body you wish to destroy into an array
 destroy_list.push(body);
}

// The game interval function
var update = function () {
  // Destroy all bodies in destroy_list
  for (var i in destroy_list) {
    world.DestroyBody(destroy_list[i]);
  }
  // Reset the array
  destroy_list.length = 0;
}
Run Code Online (Sandbox Code Playgroud)