# How to simulate planetary gravity.

The most important thing you need to know when simulating planetary gravity is Newton law of universal gravitation. Which states that every point mass in the universe attracts every other point mass with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between them.

Where: G stand for Gravitational Constant, m1 & m2 stand for mass of the first and second object respectively, d^2 stands for the distance squared. The distance is measured from the origin of each mass object.

The law of universal gravitation is an example of an inverse square law because of the magnitude of the force is inversely proportional to the square of the separation. If the masses are moved twice as far apart, the force of gravity is cut by a factor of four. Triple the separation and the force is nine times weaker.

The gravitational constant of our universe is outlined here. In a game simulation you would want to make this a bigger number which you would tweak to make it “feel” good.

In the accompanying source code i used a Gravitational Constant of 0.5 to make it more fun to play with. Important to note when implementing planetary gravity is that the gravitational force does not depend upon the size or the density of the two bodies, provided their mass distribution is spherical. It doesn’t even depend upon the speed of motion of the two bodies. It only depends on their separation and masses.

Implementation:

The function parameters ‘p2’ and ‘m2’ are the properties of the other body. Position and Mass.

```public void UpdateGravity(Vector2 p2, float m2)
{
position += velocity * UniversalGravitation.force;
UniversalGravitation.distance = Vector2.Distance(p2, position);
UniversalGravitation.force = (UniversalGravitation.gravitationalConstant * mass * m2) /
(UniversalGravitation.distance * UniversalGravitation.distance);
UniversalGravitation.direction = (p2) - (position);
UniversalGravitation.direction.Normalize();
velocity += UniversalGravitation.direction * UniversalGravitation.force;
}
```

The source code is in C# although it can be applied to any language or framework. I Used the XNA/Monogame framework.

Source Code: