# How to program gravity for planets?

I want to make a 2-D platformer/puzzle game involving multiple small “planets” similar to Super Mario Galaxy. How would I go about programming gravity for these planets so that the closest large planet pulls the player towards it (like in real life)?

Also, I’m running into a bit of trouble programming the movement script for this as well. So if anyone knows how to move the player in a circular motion, that’d be great.

This is the formula for calculating gravitational force: gravitational_force = gravitational_constant * ((mass1 * mass2) / squared_distance_between_objects)

``````foreach planet
gravitational_constant = 100  <-- make something up here until you get pleasing results
distance_squared = (planet.position - player.position).sqrmagnitude

// get the masses - note that the planet mass needs to be much larger than the player mass
// and make sure these values are set on the rigidbody so the Unity physics will act correctly
// when the force is applied
mass1 = planet.mass = 1000    <-- mess around with these until you get pleasing results
mass2 = player.mass = 1       <-- this can probably always stay 1 for the player

force = gravitational_constant * ((mass1 * mass2) / distance_squared);

// e.g. plugging in the values...
// force = 100 * ((1000 * 1) / distance_squared)

// apply the force from the player toward the planet
force_direction = (planet.position - player.position).normalized;
force_vector = force_direction * force;

// TODO : use AddForce or whatever to apply force_vector to the player's rigidbody
// you end up adding each force vector to the player so it will move toward the
// strongest/closest/most_massive planet.
``````

Basically the force is the object masses multiplied together, then scaled by the distance between the bodies, then adjusted by the gravitational constant. You can change the mass of each planet based on its sized to make larger planets have a larger attraction.

you can add a constant force pulling the player to the centre of the planet, and if the player is a certain distance from the planet, the constant force can be turned off or reduced relative to distance, like that he will always be attracted to the centre of the planet and if he goes far enough away he will be in free space. it also means that if you freefall in the planet’s atmosphere you will accelerate into the ground and if you jump in the air it will be the same as gravity, except towards the centre.

you can add a constant force pulling the player to the centre of the planet, and if the player is a certain distance from the planet, the constant force can be turned off or reduced relative to distance, like that he will always be attracted to the centre of the planet and if he goes far enough away he will be in free space. it also means that if you freefall in the planet’s atmosphere you will accelerate into the ground and if you jump in the air it will be the same as gravity, except towards the centre.