如果我有一个游戏项目,我正在使用box2d。现在在我的MovementSystem中(我正在使用基于实体组件的方法),我想让Box2D根据控件设置的期望速度来移动我的对象。
不幸的是,速度似乎永远不会变得足够高。例如,即使在每个轴的速度矢量(期望速度)为245044.23的情况下进行applyLinearImpulse,最终得到的身体速度也就变成了关于90.0的东西。我做错了什么?有什么限制吗?
下面是我运行速度更新和world-step的代码:
//************************
// physics-system
//************************
public void update(float deltaTime) {
float frameTime = Math.min(deltaTime, 0.25f);
accumulator += frameTime;
if (accumulator >= MAX_STEP_TIME) {
world.step(MAX_STEP_TIME, 6, 2);
accumulator -= MAX_STEP_TIME;
for (Entity entity : entities) {
TransformComponent transform = tim.get(entity);
BodyComponent bodyComp = bod.get(entity);
VelocityComponent velocity = vel.get(entity);
Vector2 bodyVelocity = bodyComp.body.getLinearVelocity();
float velChangeX = velocity.horizontalVelocity - bodyVelocity.x;
float velChangeY = velocity.verticalVelocity - bodyVelocity.y;
float impulseX = bodyComp.body.getMass() * velChangeX;
float impulseY = bodyComp.body.getMass() * velChangeY;
bodyComp.body.applyLinearImpulse(new Vector2(impulseX, impulseY), bodyComp.body.getWorldCenter(),
false);
// update transform
Vector2 position = bodyComp.body.getPosition();
transform.x = (int) position.x;
transform.y = (int) position.y;
// slowingdownVelocitys(velocity);
}
}
}这里定义了我当前唯一具有box2D组件的实体(称为BodyComponent):
Entity entity = new Entity();
//...
BodyComponent bodyComponent = new BodyComponent();
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(transformComponent.getX(), transformComponent.getY());
bodyComponent.body = GameManager.getB2dWorld().createBody(bodyDef);
bodyComponent.body.applyAngularImpulse(50f, true);
CircleShape circle = new CircleShape();
circle.setRadius(2f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 10f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
bodyComponent.body.createFixture(fixtureDef);
circle.dispose();
entity.add(bodyComponent);
//... 发布于 2017-07-04 04:14:12
Box2D确实限制了速度,是的。这里的限制基本上是为了避免floating point arithmetic的不准确。正如你已经发现的,步长为1/60秒的245044.23速度远远超过了这个极限。如果你能把你的步长降低到1/200000秒,你可以模拟245044.23米每秒,但我认为我们大多数人都很难实时运行。以每秒60步的步速(每一步只是模拟秒的1/60 ),您所说的速度大约是每步4084米,因为Box2D单位基本上是MKS单位(米、公斤、秒)。同时,速度限制为每步2米(由b2_maxTranslation限制)。这个限制可以增加,但随着它的增加,您更有可能看到不太像隧道这样的物理行为。
至于你做错了什么,除了试图使用比Box2D可以处理的速度更高的速度之外,通常情况下,你所描述的问题都是由于所使用的视觉缩放造成的。请记住,Box2D的位置是以米为单位的,而我们的大多数显示器(无论是水平还是垂直方向)都比一米小得多。Box2D常见问题解答是这样说的:about scaling in terms of pixels
假设你对一个100x100像素的字符有一个子画面。您决定使用0.01的比例因子。这将使字符物理框为1m x 1m。所以去做一个1x1的物理盒。现在假设字符开始于像素坐标(345,679)。因此,将物理方框定位在(3.45,6.79)。现在模拟物理世界。假设角色物理框移动到(2.31,4.98),因此将角色精灵移动到像素坐标(231,498)。现在唯一棘手的部分是选择比例因子。这真的取决于你的游戏。你应该试着让你的移动物体在0.1 - 10米的范围内,1米是最佳位置。
你想要回答的问题是,使用什么样的缩放比例,以便Box2D可以处理的物理速度可以转换为仍然可以看到的视觉效果。在1/60秒(每一步)的阶跃模拟中,Box2D将处理的速度限制为+/- 120米每秒。但通过巧妙地在世界坐标和图形坐标之间进行缩放,这可以达到每秒120个单位的距离,您可以将距离单位设置为千米或太米或其他任何单位。
注意,非常慢的速度也会带来问题-比如遇到碰撞响应的速度阈值(b2_velocityThreshold)。
希望这能有所帮助!
https://stackoverflow.com/questions/44866044
复制相似问题