user891123
user891123

Reputation: 391

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

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() );

Upvotes: 3

Views: 3437

Answers (2)

Emmett Butler
Emmett Butler

Reputation: 6207

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.

Upvotes: 1

Andrew
Andrew

Reputation: 24846

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() );

Upvotes: 2

Related Questions