17
Mar 10

Gravity in Box2D

I’ve been using Box2DFlash for quite a few years now. One thing I have always done is set the gravity for the world without thinking about it too much. If I need things to fall down in a game then gravity has got to be the answer. When I made games with shooting in them, I started to have problems. It’s easy to make a small object in Box2D that acts as a bullet but if gravity is applied to the bullet it stops going in a straight line when you fire it out of a gun and curves down to the ground instead.

Of course this is perfectly accurate and is what happens in the real world but in games you tend to want bullets to go in a straight line. There are two ways round this problem:

The first is to turn gravity off completely. Any objects that do need to have gravity applied to them can have a downward force applied during each step that you update the Box2D model. This is great if you’ve just got a few objects that need to react to gravity and most of the rest of the game is static. This line of code applies GRAVITY to the body where the constant GRAVITY is a predefined b2Vec2 vector

const GRAVITY = new b2Vec2(0, 9.81);
myBody.ApplyForce(GRAVITY, myBody.GetPosition());

The second method is useful when most things need to react to gravity. You can ‘turn off’ gravity on certain objects by applying a force in the opposite direction to the objects that shouldn’t react to gravity. It’s the same code as above but with the direction of the gravity vector changed:

const ANTI_GRAVITY = new b2Vec2(0, -9.81);
myBody.ApplyForce(ANTI_GRAVITY, myBody.GetPosition());

When I started using Box2D, I tended to take the way it worked as something you didn’t touch. It just did it’s simulation and that was what you were stuck with. Nowadays I’m far more inclined to hack into the way it works with these kind of tricks. I also love controlling the way objects jump up and fall down to give them a more responsive feel by directly altering their velocities according to what state they are in. The true physics model is no longer sacred for me :)

Copyright © 2012 The Daily Flash
Proudly powered by WordPress, Free WordPress Themes, and Linux Hosting