Table of Contents### Gravity

#### Real Gravity

#### Good-Enough Gravity

Entire Site

Gravitational forces are what keep you on the ground and the planets in motion around the sun. Newton postulated that every particle in the universe exerts a force on every other particle in the universe. Massive bodies, such as planets, have an enormous number of particles. All of these particles attract each other, and attract you as well. In this section we're going to discuss two ways to treat gravity mathematically: the “right” way and the “good-enough” way.

The gravitational force experienced by two objects is calculated by using the equation

F = G*(mass1*mass2)/distance^{2}

F is the force felt by either object (remember Newton's third law—equal but opposite). The value G is called the constant of universal gravitation. For mathematical reasons having to do with absorbing constants into other constants (I hope you'll take my word for this one), we can just assume that G has a value of 1. The value distance is the distance between the centers of the two objects.

You are most likely never going to need to apply this realistic treatment of gravity in your games. However, if you would like to see a working example of this in Flash, then take a look at a Flash 5 experiment of mine in realGravity.fla in the Chapter04 directory. There is ActionScript in realGravity.fla that handles collision detection, collision reaction, and gravity.

As I mentioned at the beginning of this chapter, there are times when a simplified formula will do for our gaming purposes as well as the complicated, “real” physics I paid a lot of money to learn about in graduate school. We have come to one of those times now. If you've been worrying about having to work through the gravity equations, you'll be happy to hear that there is an easy way to add a gravity effect to your games: Simply come up with a value for gravity—let's say 2—and then add that value to your y velocity in every frame.

To see an example of this, open bounce.fla in the Chapter04 directory on the CD. In this file, I've affected a ball's velocity using faked gravity. I've also added a simple collision-detection trick so that the ball doesn't fall through the floor (we'll talk more about that in Chapters 5 and 6, “Collision Detection” and “Collision Reactions”). Here is the ActionScript: |

1 ymov = 0; 2 //set gravity 3 gravity = 2; 4 _root.onEnterFrame = function () { 5 ymov += gravity; 6 ball._y += ymov; 7 if (ball._y > 400) { 8 ball._y = 400; 9 ymov *= -1; 10 } 11 }

As you can see in line 5, gravity is used to change the ball's velocity in the same way that acceleration was used to do this. In lines 7 through 10 we check to see if the ball is below 400 (which is the height of the floor on the stage in this movie). If so, then it is off the screen, and we set its position back to 400 and reverse the y velocity, `ymov`. The final result is a ball that bounces in place.