Body 在 C++ 的 Box2D 中添加关节后更改其位置

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

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

代码:

#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

我觉得应该return

[ 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),它不应该移动两个物体。

您的代码未设置 b2BodyDef position 字段,因此两个主体都在默认位置 Vec2(0, 0) 创建(根据 b2BodyDef b2Body.h 文件中的结构定义)。根据您的代码设置 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)的世界位置)。