在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
我认为它应该返回
[ body 1 ] 0 (before step)
[ body 2 ] 0
[ body 1 ] 0 (after step)
[ body 2 ] 1
也许我的代码有问题?我是Box2D的新手。我该怎么做才能得到预期的结果?
步骤前,body 1
和body 2
的位置为(0, 0)
。我认为它应该在步骤后自动将body 2放置到(1, 1)
,它不应该移动两个body。
您的代码没有设置b2BodyDef
position
字段,因此两个主体都在Vec2(0, 0)
的默认位置创建其中心(根据b2Body.h
文件中的b2BodyDef
结构定义)。根据您的代码设置localAnchorA
和localAnchorB
的位置,我怀疑您创建主体的代码需要更像:
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
polygonShape
在Vec2(0.0f, 0.0f)
居中,你的body2
polygonShape2
在前一个形状的右上角居中,而连接两个主体的锚点就在同一个角上(Vec2(1.0f, 1.0f)
的世界位置)
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我的点没有在 OpenGL 中绘制鼠标所在的位置?
- 如何将元素添加到向量的字符串位置
- 如何选择在 csv 文件中输出的位置
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何在特定位置追加 json 文件
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序