我正在使用Box2D通过Libgdx创建一个场景。我有一个场景,我想使用applyForce
不断推进一个特定的对象(方向会不时变化),但只能达到给定的速度。
想象一下由火箭发动机推动的圆形物体(所有侧面都有喷嘴),零G,以供说明。
有没有办法在不重新计算所施加的力或每次更新时重复计算的情况下执行此操作?我只知道如何为所有对象设置最大速度。我目前最好的选择是以某种方式使用linearDamping
,但我希望有一个更简单的解决方案。
答案 0 :(得分:9)
您可以使用SetLinearVelocity覆盖当前速度。
b2Vec2 vel = body->GetLinearVelocity();
float speed = vel.Normalize();//normalizes vector and returns length
if ( speed > maxSpeed )
body->SetLinearVelocity( maxSpeed * vel );
===============
编辑: 简单的空气阻力可以通过在相反的行进方向上施加小的阻力来建模,与行进速度成比例。
b2Vec2 vel = body->GetLinearVelocity();
body->ApplyForce( 0.05 * -vel, body->GetWorldCenter() );
阻力的刻度值(本例中为0.05)决定了阻力等于火箭发动机施加的力的速度,两个力相互抵消,达到最高速度。
maxSpeed = thrustForce.Length() / 0.05;
纯粹主义者会指出阻力实际上是相对于速度的平方,所以为了更准确你可以这样做:
b2Vec2 vel = body->GetLinearVelocity();
float speed = vel.Normalize(); //normalizes vector and returns length
body->ApplyForce( 0.05 * speed * speed * -vel, body->GetWorldCenter() );
......我认为这会给你一个最快的速度
maxSpeed = sqrtf( thrustForce.Length() / 0.05 );