Szymon Marczak Szymon Marczak - 3 months ago 16
C++ Question

Body changes its position after adding joint to it in Box2D in C++

When I create a joint between two bodies, their position changes. I don't create any forces.

Code:

#include <iostream>
#include <Box2D/Box2D.h>

int main() {
// WORLD
b2World world(b2Vec2(0, 0));

// BODY DEF
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

// SHAPES
b2PolygonShape polygonShape;
polygonShape.SetAsBox(1, 1);

b2PolygonShape polygonShape2;
polygonShape2.SetAsBox(0.5, 0.5);

// BODY 1
b2Body* body = world.CreateBody(&bodyDef);
b2Fixture* fixture = body->CreateFixture(&polygonShape, 1);

// BODY 2
b2Body* body2 = world.CreateBody(&bodyDef);
b2Fixture* fixture2 = body2->CreateFixture(&polygonShape2, 1);

// JOINT
b2RevoluteJointDef jointDef;
jointDef.bodyA = body;
jointDef.localAnchorB.SetZero();

jointDef.bodyB = body2;
jointDef.localAnchorA.Set(1, 1);
b2Joint* joint = world.CreateJoint(&jointDef);

// LOGS (X POSITION)
std::cout << "[ body 1 ] " << body->GetPosition().x << std::endl;
std::cout << "[ body 2 ] " << body2->GetPosition().x << std::endl;

world.Step(1 / 50.0f, 8, 3);

std::cout << "[ body 1 ] " << body->GetPosition().x << std::endl;
std::cout << "[ body 2 ] " << body2->GetPosition().x << std::endl;
return 0;
}


Output (
x position
):

[ body 1 ] 0 (before step)
[ body 2 ] 0
[ body 1 ] -0.2 (after step)
[ body 2 ] 0.8


I think it should return

[ body 1 ] 0 (before step)
[ body 2 ] 0
[ body 1 ] 0 (after step)
[ body 2 ] 1


Maybe something's wrong in my code? I'm new in Box2D. What I should do to get the expected result?

Before the step the position of
body 1
and
body 2
is
(0, 0)
. I think it should place body 2 to
(1, 1)
automatically after the step, it shouldn't move both bodies.

Answer

Added

body2->SetTransform(body->GetPosition() + joint->GetAnchorA(), body2->GetAngle());

before calling world.Step. It places the second body on its correct position. If it isn't correct, 'invicible' force moves it to its correct position.