# Need help with gravity engine

This is a discussion on Need help with gravity engine within the Game Programming forums, part of the General Programming Boards category; I need help creating code for a "gravity engine." This is a tanks style game, so I need to get ...

1. ## Need help with gravity engine

I need help creating code for a "gravity engine." This is a tanks style game, so I need to get the gravity around a point. I cannot seem to implement velocity and, more specifically, acceleration. Can someone help me grasp the theory?
!I don't need code, just the math.!

2. That's not quite what I mean. I know that the force is calculated by (G*Mass1*Mass2)/(Distance), AKA, I know how to get the force of gravity on the particle, but I dont know how to apply the force onto the object. How does a force of gravity affect the velocity? Do I average it with the current velocity? Do I use a weighted average?

Perhaps I do need code after all.

3. Force is a change in momentum. Calculate the force according to your equations. Momentum is a vector quantity, so you just vector add the change in momentum to the current object's momentum. You don't really need to update momentum because this is gravity i.e, at sea level, the acceleration due to gravity is a constant 9.8 M/s^2, which is equal to G * M2 / (r^2) where G is the constant, M2 is the point mass affecting your object, r is distance squared (you already seem to know this stuff), but in general it's a good idea to get used to updating momentum for physics simulations.

You know the object's mass.
Momentum = Mass*Velocity according to the Newtonian view of things (otherwise according to the relativistic approach you have to take into account a term that involves the change in mass which occurs near relativistic velocities, but that's utterly useless for this application). You solve for the velocity based on the current momentum. Once you've got the velocity, you update the position.

There are various ways to 'update' these quantities by the way. In rigorous physics applications you typically have to write a numerical differential equation solver which adds terms to a taylor series polynomial, but I suggest just taking what's called the Euler approach, like this:

Code:
```//psuedocode
float DeltaTime = .01; // the timestep for the physics application, this is typically a constant for rigorous physics applications,
//but otherwise is calculated based on the time passed since the last physics frame was rendered
Vector Force = (G * M1 * M2) / DistanceSquared;//vector quantity which points from M1 towards M2 (when applied to M1)

Object.Momentum += Force * DeltaTime; //integrate momentum
Object.Velocity = Object.Momentum / Object.Mass;
Object.Position += Object.Velocity * DeltaTime;```
I don't want to answer all of the details that go into implementing this because it won't help you, which is why I have written invalid code and left a lot of things blank, but I also appreciate how hard it is to get started on writing physics stuff (in my opinion, much much harder than writing graphics software).

Feel free to ask stupid questions, or send me a private message if you'd prefer. Otherwise you should be able to find this online.

4. Thanks, this has helped a lot. One last question: Which gives a smaller headache, keeping track of velocity in magnatude and angle, or X and Y velocities? There may be not much of a difference, but I am realising this is an ambitious first project.

Thanks again.

5. Well, what do you think would give less of a headache? How would you update the position of the object if you store the velocity as a magnitude/angle? Would this be any different from storing the velocity as a vector with the X,Y components? What would be the easiest way to augment your program to three dimensions?

The reason I'm being a dink and answering a question with more questions is because both methods work and are objectively 'good' but you need to think about this stuff yourself as much as possible, in order to get good (which you will).

6. I understand completely. I was just asking in case there are any catastrophic problems one way or another.

You would tell me about any big problems... right?

7. There are not any catastrophic problems with storing the velocity as a magnitude/angle. Personally, I keep everything as a vector. Why do I keep everything as a vector? Because I store the position as a vector, and if I were to store the velocity as a magnitude/angle then I'd need to just convert the magnitude/angle to <X,Y> components before updating the position (using basic trig), so it makes sense to just store the velocity as a vector with <X,Y> components in the first place. Both work fine though, especially in 2D. In 3D, it becomes very unattractive to store the velocity vector as three angles, but it can be done.

So, in case I wasn't clear, you shouldn't be running into any catastrophic problems, this is a judgement call on your part.

Don't be afraid to implement both, it'll do nothing but give you more experience.

8. Wow never thought I'd see the stuff I learned in physics class exactly stated, if you need more help let me know because I have definetly just taken a year of physics so its fresh.

You sure you need to calculate the particle gravitational force? Why not just use basic physics ie 1/2at^2 + Vo(t) for the gravitational pull and acceleration.

9. Your equation assumes the acceleration vector remains continuous, which is not correct. The acceleration vector is a function of position relative to the point mass (well, the distance squared). Likewise, the position is a function of the acceleration. There is no way that I know of to just plug the time into an equation to solve for position at any point in time (although there may be a chapter on Kepler's equations of planetary motion that has just such a thing in my calculus book, but it still wouldn't really be practical if you wanted the simulation to be interactive, i.e, if you wanted to fly a spaceship within a pertinent gravity field, and I don't think the solution would be particularly intuitive).

EDIT:
as I suspected, in order to model planetary motion using continuous equations an approach completely different from what you suggested is used. Instead of using the traditional equations of motion, polar coordinates are used with not-so intuitive equations which solve for radius with respect to time.

10. Physics for Game Developers

www.amazon.com

The velocity should be stored as a vector. I cannot imagine why you would not want to do this. The vector should be normalized so that operations do not yield huge values.

And you can find distance and position using the simple:

rt=d

This is in the form of f=ma and you can use it to find position as long as you know two pieces of information: rate and time. In fact most physics engines work like this and will use integrals of time - if the integral is empty, or the time is infinite in the integral, then two objects will definitely not come into contact within that frame.

I'm not sure why all the fuss as those equations are just fundamental physics. If you want to take into account the mass then you must add up all the point masses to arrive at the mass moment of inertia. This can be done by approximating your object's mass profile by using volumes to enclose the geometry of your object - the mass of these volumes are easy to calculate - and you can even find the mass moment of inertia for those masses as well. Average the point masses and you have the mass portion finished.

11. if the integral is empty, or the time is infinite in the integral, then two objects will definitely not come into contact within that frame
The term is temporal coherence.

I'm not sure why all the fuss as those equations are just fundamental physics.
Because JoshR was implying there may exist an equation that gives the exact position of a point mass in a gravity field at any point in time, and technically he is correct, just the equations aren't particularly practical, but it's a fair point to bring up as numerical differential equation solvers are only approximations, and while solvers such as improve euler and multiple degree runge kutta typically converge on the proper solution (typically for position, but you can also integrate matrices and quaternions, or really any mathematical entity) they're still just approximations.

If you want to take into account the mass then you must add up all the point masses to arrive at the mass moment of inertia
Mass moment of inertia is a tensor that applies when grappling with rotational physics. If you want to take into account mass, you assign a value to the mass variable, or you assign a density and a volume, not compute the mass moment of inertia, lol. The moment applied from gravity is inconsequential in the real world, subsequently it's even less important in a computer program's gravity engine.