开发者

How to make a b2body move at a constant speed with box2d

开发者 https://www.devze.com 2023-04-08 17:11 出处:网络
I am making a box2d game and have enemies fly in from the left side of the screen to the right side of the screen. If I apply a force in the tick method like shown below, the enemies increasingly move

I am making a box2d game and have enemies fly in from the left side of the screen to the right side of the screen. If I apply a force in the tick method like shown below, the enemies increasingly move faster over time. I want the enemies to move at a constant pace instead of increasing their speed. How can I do this. I have tried impulses and forces, but they don't seem to 开发者_如何学编程keep a constant speed

b2Vec2 forceA = b2Vec2(15, -b->GetMass() * world->GetGravity().y);
b->ApplyForce(forceA, b->GetWorldCenter() );


Just create them with the speed you want:

b2BodyDef bDef;
...
bDef.linearVelocity = myVelocity;
b2Body *b = world->createBody(&bDef);

If no forces are applied to them they will preserve their speed according to Newton's first law. If you have gravity then each step apply force:

b2Vec2 forceA = b2Vec2(0, -b->GetMass() * world->GetGravity().y);
b->ApplyForce(forceA, b->GetWorldCenter() );


use b->SetLinearVelocity(b2Vec2(thisVel, 0));. If this constant velocity might eventually be changed for some other constant velocity, you could wrap this in a conditional such as

if(b->GetLinearVelocity().x != 0){ 
    b->SetLinearVelocity(b2Vec2(0, 0));
}

So that you're not re-applying the same velocity each tick (although it's possible that box2d takes care of this for you, not sure about that).

I ran into the same issue of how to make bodies move at a constant speed, and the one other thing I recommend is to make sure the surface/medium that your body is moving across is frictionless - that way they'll never slow down after you set their velocity.

0

精彩评论

暂无评论...
验证码 换一张
取 消