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

接着上次的文章

在很多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() );

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值