BOX2D 自然的移动到一个指定速度

手机游戏源码VIP金牌  一次购买全店免费!

接着上次的文章

在很多BOX2D游戏中同样会遇到这样一个问题:

如何使一个body自然的按照一个指定速度移动?

 

方法同上次所说的有三种:

1-直接设定body的线速度

这是最直接的方法,但是同样的,并不是在box2d中最好的方法

b2body *body;// the body you want to conroll
b2Vec2 vel;// the vel you set
body->SetLinearVelocity( vel );

这样做,如果只有一个物体,你可以得到你想要的效果,但是如果有许多body,你会发现很多不符合物理规律的现象,这是由于你改变了body正在模拟的物理属性。

 

2-对body施加一个作用力

这种方法较前者更优,用到了动量定理ft = mv。

已知一个物体的初速度vel,和物体质量body->GetMass(),你要设定他t秒后的速度要变为desiredVel的话,可以计算出需要的力f=(v2-v1)*m/t
代码如下:
复制代码
b2Vec2 vel = body->GetLinearVelocity();
float m = body->GetMass();// the mass of the body
float t = 1.0f/60.0f; // the time you set
b2Vec2 desiredVel = b2Vec2(10,10);// the vector speed you set
b2Vec2 velChange = desiredVel - vel;
b2Vec2 force = m * velChange / t; //f = mv/t
body->ApplyForce(force, body->GetWorldCenter() );
复制代码

这里得到的效果应该是和设定速度是一样的,但是如果有多个物体时,能够正确模拟碰撞对物体产生的效果。

 

3-对body施加一个冲量

这种方法本质上和施加力是一样的,但是可以不用考虑时间因素

b2Vec2 vel = body->GetLinearVelocity();
float m = body->GetMass();// the mass of the body
b2Vec2 desiredVel = b2Vec2(10,10);// the vector speed you set
b2Vec2 velChange = desiredVel - vel;
b2Vec2 impluse = m * velChange; //impluse = mv
body->ApplyLinearImpulse( impluse, body->GetWorldCenter() );

最终效果也能够让人满意。

猜你喜欢

转载自blog.csdn.net/looffer/article/details/8951334