I’m sure you’ve seen a game where a planet with its own gravity was used. In fact, this effect is actually simpler than you probably think. So how to do it?


STEP 1 – Create a planet

The first thing we should do is to create a planet that will attract our objects. Don’t forget to add Circle Collider 2D to keep the objects from falling through the planet. The object that will be attracted should have a Box Collider 2D and Rigidbody 2D component, in which we set the Gravity Scale value to zero.

STEP 2 – Measure the distance between the object and the planet

If you want gravity to take effect only from a given distance, we need to measure the distance between the planet and the object. Therefore, we need to declare the variable public GameObject planet; to know where the planet is. The Vector3.Distance(a, b); command will allow us to find the distance between the objects, so the code should look like this:

using UnityEngine;

public class PlanetGravity : MonoBehaviour
{

    public GameObject planet;

    void Update()
    {   

        float dist = Vector3.Distance(planet.transform.position, transform.position);
    }
}

STEP 3 – Programming of gravity

Now the most important part – How to program gravity to the center of the planet? Before we can answer this question, we first need to declare the variables public float gravityDistance;, public float gravityForce; and Rigidbody2D rb;. We need to find out which direction the center of the planet is located, so we use the planet.transform.position - transform.position; command to do this. Finally, we just need to use the command Rigidbody2D.AddForce(); to create a so-called false gravity. This is what the code looks like:

// Insert the final code into each object you want the planet to attract.

using UnityEngine;

public class PlanetGravity : MonoBehaviour
{
    Rigidbody2D rb;

    public float gravityDistance = 150.0f;
    public float gravityForce = 50.0f;

    public GameObject planet;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {   
        // Distance to the planet
        float dist = Vector3.Distance(planet.transform.position, transform.position);


        Vector3 v = planet.transform.position - transform.position;


        // Gravity
        rb.AddForce(v.normalized * (1.0f - dist / gravityDistance) * gravityForce);
    }
}