# Setting the Box2D gravity for a pixel coordinate game?

I'm making a game with Box2D with a top left coordinate system. I multiply positions by an M_TO_PX_RATIO of 10.0f to convert from meters to pixels.

I noticed that when I set gravity to 9.8, the simulation is rather slow. When I set gravity to 9.8 * M_TO_PX_RATIO, the simulation runs at the correct speed, like normal gravity. However, the high gravity causes jittering.

Am I doing it properly? When using a top left, pixel coordinate system, must I do anything else to account for meters to pixels?

Thanks

• What is a "pixel coordinate game"? Also, how do you define "rather slow"? Is this a performance problem, or are objects simply not moving as fast as you expect? – Nicol Bolas Jul 21 '11 at 0:30
• @Nicol It is not performance, they just do not move nearly as fast as real life. It only looks fast enough if I set gravity to 100 instead of 10. By Pixel I mean that when I draw something at 10,10 I see it at pixel 10,10 on the screen. I tried setting my ratio to 32 and gravity to 10 but it still has a smooth slo mo feel. – jmasterx Jul 21 '11 at 0:35
• Is there any particular reason you're not using metres, considering that a) Box2D is tuned for metres/kilograms/seconds and b) it's more understandable for both you and I than pixels as a measurement of distance, and it could immediately tell you what's going on (e.g. maybe it's going a magnitude slower because your scale is a magnitude too large, so you're seeing a fall take place that's ten times larger than you intend) – doppelgreener Jul 21 '11 at 0:47
• If your simulation looks fine with a Gravity of 100, why not do that? As for the jittering: Increasing the iterations in one step should fix that. Btw. How big are your objects (in Box2d units)? – bummzack Jul 23 '11 at 8:28

## 1 Answer

Box2D is a meter-based physics engine, and as such, it would not behoove you to try to force it to "snap" to pixels. The easiest way to get around this is simply allow Box2D to calculate all of the physics in the background, and simply render all of your pixel sprites to the screen at the closest pixel coordinate (I like to floor my x and y value to prevent sprite jitter).

Here's an extremely simple psudo-code version of what I'm trying to explain:

// Draw function
mySprite.render(Floor(calculatedXLocation), Floor(calculatedYLocation));


This will give the illusion of the sprite being locked to the pixel grid, but will allow your physics to run however you want them to run without being hampered by an odd time-step or gravity.