Box2D机构之间的层次连接

时间:2016-03-16 15:29:15

标签: c++ box2d box2d-joints

我在box2d中有一个任意深度的树体结构。当父体碰撞任何东西时,它应该移动它的孩子。另一方面,如果孩子因碰撞而移动,则不应触摸父母。一个身体可以是一个身体的父母,一个孩子可以同时是另一个身体。

有没有办法在Box2D中实现这个?没有一个关节似乎能够代表这一点,因为它们都是对称的。

1 个答案:

答案 0 :(得分:2)

是。从算法上讲,使用概念上嵌套的世界。

这是一些伪代码。您需要填写详细信息,例如将机构设置为动态以及密度应该是多少。但希望代码能够显示完成此任务的方法:

extern void render(b2World& world, b2Vec2 position);

b2World world(b2Vec2(0, 0));
b2World subWorld(b2Vec2(0, 0));

b2BodyDef bodyDef;

// Create body outside of "parent".
bodyDef.position = b2Vec2(-15, 14);
b2Body* otherBody = world.CreateBody(&bodyDef);

// Setup "parent" body.
b2Body* parentBody = world.CreateBody(&bodyDef);
b2Vec2 vertices[] = { b2Vec2(10, 10), b2Vec2(-10, 10), b2Vec2(-10, -10), b2Vec2(10, -10) };
b2PolygonShape parentShape;
parentShape.Set(vertices, 4);
b2FixtureDef parentFixtureDef;
parentFixtureDef.shape = &parentShape;
parentBody->CreateFixture(&parentFixtureDef);

// Setup container for bodies "within" parent body...
b2BodyDef childBodyDef;
// set childWorldBody to being static body (all others dynamic)
b2Body* childWorldBody = subWorld.CreateBody(&childBodyDef);
b2ChainShape containerShape;
containerShape.CreateLoop(vertices, 4);
b2FixtureDef childContainerFixture;
childContainerFixture.shape = &containerShape;
childWorldBody->CreateFixture(&childContainerFixture);

// First example of creating child body "within" the parent body...
childBodyDef.position = b2Vec2(0, 0); // Inside child world and with childContainerShape.
b2Body* bodyInChild = subWorld.CreateBody(&childBodyDef);
// Call subWorld.CreateBody for all the bodies in the child world.
// Always create those child bodies within the bounds of vertices.

for (;;)
{
    world.Step(0.1, 8, 3);
    subWorld.Step(0.1, 8, 3);

    render(world, b2Vec2(0, 0));
    render(subWorld, parentBody->GetPosition());
}