Gravity

While some games (such as Pong) ignore gravity, some (such as Pinball games) rely on it heavily. Implementing gravity is pretty easy if you remember a little physics and a little calculus. The physics is remembering that gravity is a type of acceleration. Calculus comes in to remind you that acceleration is change in velocity. So, we simulate gravity by changing our velocity by a fixed amount each time through the animation loop. If gravity is pulling downwards (a standard arrangement), then it causes no change in the dx component of our velocity. We can set g to some fixed amount and each time through the loop, after we've update x and y by adding dx and dy, we then update dy by adding g:


  x = x + dx;  y = y + dy;
  dy = dy + g;

That's all there is to it!

Like in the discussion of movement, how accurately you can compute things affects how good your simulation is. Integer values may be good enough in some case, but most likely you'll want to use floating point values to store the position, velocity, and acceleration.

Of course, one of the great things about video games is that your game world does not have to behave just like the real world. What if we wanted gravity to pull upwards? Well, that just means that g should be a negative number (since the y-axis on the screen has larger y values down and smaller y values up). In fact, if we let gx and gy be components of a gravity vector pointing in any direction we like, we can make gravity pull in that direction by adding gx to dx and gy to dy. There was a game when I was in college (whose name I can't recall) which even had gravity pulling in towards the middle of the screen. At each step, you figure out a gravity vector pointing towards the center and then use that to update the velocity. If this is done accurately enough, you can even put objects in orbit around the center of the screen!


Back to course home page.