简体   繁体   English

如何在libgdx / box2d中为特定主体强制执行最大速度?

[英]How to enforce a maximum speed for a specific body in libgdx/box2d?

I'm using Box2D through Libgdx to create a scene. 我通过Libgdx使用Box2D来创建场景。 I have a scenario where I would like to constantly propel a specific object using applyForce (the direction would change from time to time), but only up to a given speed. 我有一种情况,我想使用applyForce不断推进特定对象(方向会不时变化),但只能达到给定速度。

Picture a circular object propelled by a rocket motor (with nozzles on all sides), in zero G, for illustration. 图示一个由火箭发动机推动的圆形物体(在所有侧面带有喷嘴),其零零G形状用于说明。

Is there a way to do this without recalculating the force applied, or performing a repeated calculation each update? 有没有一种方法可以在不重新计算施加力的情况下或在每次更新时都进行重复计算? I only know how to set a maximum speed for all objects. 我只知道如何为所有对象设置最大速度。 My best bet at the moment is to use linearDamping somehow, but I'm hoping there's a simpler solution. 目前,我最好的选择linearDamping某种方式使用linearDamping ,但我希望有一个更简单的解决方案。

You could override the current velocity with SetLinearVelocity. 您可以使用SetLinearVelocity覆盖当前速度。

b2Vec2 vel = body->GetLinearVelocity();
float speed = vel.Normalize();//normalizes vector and returns length
if ( speed > maxSpeed ) 
    body->SetLinearVelocity( maxSpeed * vel );

=============== ===============

EDIT: Simple air resistance can be modeled by applying a small drag force in the opposite direction of travel, scaled with the speed of travel. 编辑:可以通过在相反的行进方向上施加较小的阻力来模拟简单的空气阻力,并随行进的速度进行缩放。

b2Vec2 vel = body->GetLinearVelocity();
body->ApplyForce( 0.05 * -vel, body->GetWorldCenter() );

The scale value for the drag (0.05 in this example) determines the speed at which the drag force will equal the force applied by the rocket motor and the two forces cancel each other, giving a top speed. 阻力的比例值(在此示例中为0.05)确定了阻力的速度,该速度将等于火箭发动机施加的力,并且两个力相互抵消,从而给出最高速度。

maxSpeed = thrustForce.Length() / 0.05;

Purists will point out that drag is actually relative to the square of the velocity, so to be more accurate you could do: 纯粹主义者将指出,阻力实际上是相对于速度的平方,因此,更准确地说,您可以执行以下操作:

b2Vec2 vel = body->GetLinearVelocity();
float speed = vel.Normalize(); //normalizes vector and returns length
body->ApplyForce( 0.05 * speed * speed * -vel, body->GetWorldCenter() );

... which I think would give you a top speed of ...我认为这将为您带来最快的速度

maxSpeed = sqrtf( thrustForce.Length() / 0.05 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM