Thursday, April 17, 2014

Shooting bullets using Box2D

I got to the point where i wanted to shoot a bullet from some position toward my main character (its centroid).

To do this you have to make a little set up in the body definition:

b2BodyDef bulletBodyDef;
bulletBodyDef.type=b2_dynamicBody;
bulletBodyDef.bullet = true;

Additionally to the regular settings you have to set "isBullet" to true. This will tell Box2D to calculate collision continuosly for that body to avoid tunneling (passing through other bodies when moving too fast).

To actually shoot the bullet just apply a linear impulse to it. To calculate the direction in my case just get the vector from bullet to target, normalize it and multiply it by the magnitude of the impulse you are applying.

auto force = 10.0f;
auto hyp = target - bullet->GetPosition();
hyp.Normalize();
bullet->ApplyLinearImpulse(b2Vec2(force*hyp.x, force*hyp.y), bullet->GetWorldCenter(), true);

Once you have this you can shoot as many bodies as you want and if you are lucky enough your main character will have tons of holes :)

No comments:

Post a Comment