我正在玩box2djs。我试图找到一种方法来编写'onCollision()'回调函数,但文档很稀疏,我找不到明显的方法来做到这一点。
谢谢!
答案 0 :(得分:1)
回调box2djs实际上被称为碰撞“过滤器”。以下是如何实现它。我还会展示我正在做的事情,这可能有点慢,但由于我的另一种方法是在步骤()之外,我可以销毁对象和东西:
// Called whenever a collision occurs in the world
//
var JellyCollisionCallback = function()
{
// Required function - this is the function the gets called when b2ContactManager registers a collision between two bodies
//
this.ShouldCollide = function( shape1, shape2 )
{
// These are the two bodies…
//
var cBody1 = shape1.m_body;
var cBody2 = shape2.m_body;
// I'm setting userData when I create the body object
//
var jellyObject1 = cBody1.GetUserData();
var jellyObject2 = cBody2.GetUserData();
// This is the code from the default collision filter
//
if (shape1.m_groupIndex == shape2.m_groupIndex && shape1.m_groupIndex != 0)
{
return shape1.m_groupIndex > 0;
}
var collide = (shape1.m_maskBits & shape2.m_categoryBits) != 0 && (shape1.m_categoryBits & shape2.m_maskBits) != 0;
return collide;
}
return this;
}
function createWorld()
{
var world = new b2World(worldAABB, gravity, doSleep);
myCollisionCallback = new JellyCollisionCallback();
world.SetFilter(myCollisionCallback );
}
可能不如真正的回调那么好,但我最初在尝试回调工作时遇到了麻烦,因此我编写了这种方法并最终保留了它。我在调用world.step()
的主循环中执行此操作// Find collisions between selected objects
//
// (world is the main b2World object)
//
var aContact;
for ( aContact = world.m_contactList; aContact != null; aContact = aContact.m_next )
{
var cBody1 = aContact.m_shape1.m_body;
var cBody2 = aContact.m_shape2.m_body;
// I'm setting userData when I create the body object
//
var jellyObject1 = cBody1.GetUserData();
var jellyObject2 = cBody2.GetUserData();
// Not one of my controlled Objects
//
if ( typeof(jellyObject1) != "object" || jellyObject1 == null )
continue;
if ( typeof(jellyObject2) != "object" || jellyObject2 == null )
continue;
// Call my collision event for the colliding objects
//
jellyObject1.dink();
jellyObject2.dink();
}
文档几乎无法从我发现的内容中获得,但我真的很喜欢box2djs并且终于找到了完成一些简单的爱好项目所需的一切。以下是一些扩展原始box2djs demo jellyrobotics box2djs project
的示例