在c++的Box2D中添加关节后,物体会改变位置

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

本文关键字:体会 位置 改变 c++ Box2D 添加      更新时间:2023-10-16

当我在两个物体之间创建关节时,它们的位置会发生变化。我没有制造任何力。

代码:

#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;
}

输出(x position):

[ body 1 ] 0                                (before step)
[ body 2 ] 0
[ body 1 ] -0.2                             (after step)
[ body 2 ] 0.8
我认为它应该返回
[ body 1 ] 0                                (before step)
[ body 2 ] 0
[ body 1 ] 0                                (after step)
[ body 2 ] 1

也许我的代码有问题?我是Box2D的新手。我该怎么做才能得到预期的结果?

步骤前,body 1body 2的位置为(0, 0)。我认为它应该在步骤后自动将body 2放置到(1, 1),它不应该移动两个body。

您的代码没有设置b2BodyDef position字段,因此两个主体都在Vec2(0, 0)的默认位置创建其中心(根据b2Body.h文件中的b2BodyDef结构定义)。根据您的代码设置localAnchorAlocalAnchorB的位置,我怀疑您创建主体的代码需要更像:

b2BodyDef bodyDef1;
bodyDef1.type = b2_dynamicBody;
bodyDef1.position.Set(0.0f, 0.0f);
b2BodyDef bodyDef2;
bodyDef2.type = b2_dynamicBody;
bodyDef2.position.Set(1.0f, 1.0f);
...
b2Body* body = world.CreateBody(&bodyDef1);
...
b2Body* body2 = world.CreateBody(&bodyDef2);

这样你的body polygonShapeVec2(0.0f, 0.0f)居中,你的body2 polygonShape2在前一个形状的右上角居中,而连接两个主体的锚点就在同一个角上(Vec2(1.0f, 1.0f)的世界位置)