Creating self contained gravity for multiple planets

I’m trying to create a script that will create a gravity force on a planet, that can be applied to a prefab and then applied to whatever planet’s i create, making it so each planet’s gravity is not dependent on the existance or location of another planet for it to maintain gravity on the player.

The end desire is to provide a seamless surface of planet to space to surface of other planet transition, staying away from Parent/Child relationships between Player and Planet.

The Planet’s may not rotate and they will definitley remain in static positions, so concern for orbit is unnecessary.

any suggestions I will be highly interested in, thank you in advance!

I would do this by using a sphere with a collider set to a trigger to then maintain a list of objects within the distance which gravity applies.

Then I would calculate a direction vector by subtracting the position values between the orbiting object and the planet object. Then normalise to get a direction vector and multiply by a gravity factor, this could be based on the mass of the planet. Lastly use AddForce on the rigid body to apply this gravity force onto the orbiting object.

This is how you calculate gravitational acceleration:

/// <summary>
    /// The Newton's constant, an empirical physical constant involved in the calculation(s) of gravitational force between two bodies.
    /// </summary>
    private const float gravitationalConstant = 6.672e-11f;
   
    /// <summary>
    /// Calculates gravitational acceleration for a Rigidbody under the influence of a large "mass" point at a "position".
    /// Use this in each FixedUpdate(): rigidbody.velocity += GAcceleration(planetPosition, planetMass, rigidbody);
    /// </summary>
    /// <returns>The acceleration.</returns>
    /// <param name="position">Position of the planet's center of mass.</param>
    /// <param name="mass">Mass of the planet (kg). Use large values. </param>
    /// <param name="r">The Rigidbody to accelerate.</param>
    public static Vector3 GAcceleration(Vector3 position, float mass, Rigidbody r) {
        Vector3 direction = position - r.position;
       
        float gravityForce = gravitationalConstant * ((mass * r.mass) / direction.sqrMagnitude);
        gravityForce /= r.mass;
       
        return direction.normalized * gravityForce * Time.fixedDeltaTime;
    }

Units are m/kg/s

1 Like