Box2D hierarchical connection between bodies

I have an arbitrarily deep tree structure of bodies in box2d. When the parent body encounters something, it must move its children. On the other hand, if a child moves due to a collision, it must not be touched. One body can be the parent of one body and child to another at the same time.

Is there a way to implement this in Box2D? It seems that none of the joints can imagine this, since they are all symmetrical.

+5
source share
1 answer

Yes. Algorithmically speaking, use conceptually nested worlds.

Here is some kind of pseudo code for this. You will need to fill in the details, for example, adjust the dynamic bodies and what densities should be. But hopefully the code shows a way to do this:

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()); } 
+2
source

Source: https://habr.com/ru/post/1245171/


All Articles