如何在碰撞后删除Box2dWeb中的主体 [英] How do I remove a body in Box2dWeb after a collision
问题描述
在Update函数内部,如果2个实体发生碰撞,我想删除它们(或将它们标记为需要删除,并在时间步骤结束时删除它们)。我将如何实现这一目标?
Inside of the Update function, if 2 bodies collide I want to remove them (or mark them as needing to be removed, and remove them at the end of the time step). How would I accomplish this?
在更新功能中,我尝试
var bodyA = this.m_fixtureA.m_body;
...
bodyA.m_world.DestroyBody(bodyA);
但是,它们不会被删除。似乎当我尝试删除它们时,this.IsLocked()设置为true。
However, they don't get deleted. It seems that when I am trying to delete them, this.IsLocked() is set to true.
推荐答案
如果world.IsLocked()函数返回true,则世界不会删除实体。
而world.IsLocked()将在世界迈出一步时返回true。
在步骤中删除正文可能会导致问题,因此在碰撞后销毁物体的正确方法是将它们注册到变量中,然后在步骤完成后销毁它们。
The world will not remove bodies if the world.IsLocked() function returns true. And world.IsLocked() will return true while the world is in a step. Removing a body during a step could cause issues, so the correct way of destroying bodies after collisions is to register them in a variable and then destroy them after the step is completed.
//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;
}
这篇关于如何在碰撞后删除Box2dWeb中的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!