How to track transform.position in real time?

Hello everyone, I’m very new in Unity, in fact this is my very first project.

I’m working on a little 2d game where you control a planet to dodge incoming asteroids. I’m implementing gravity in the following manner:

public class Gravity : MonoBehaviour
{
    Rigidbody2D rb;

    Vector2 lookDirection;

    float lookAngle;

    [Header ("Gravity")]
    
    // Distance where gravity works
    [Range(0.0f, 1000.0f)]
    public float maxGravDist = 150.0f;
    
    // Gravity force
    [Range(0.0f, 1000.0f)]
    public float maxGravity = 150.0f;
    
    // Your planet
    public GameObject planet;

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

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

        // Gravity
        Vector3 v = planet.transform.position - transform.position;
        rb.AddForce(v.normalized * (1.0f - dist / maxGravDist) * maxGravity);

        // Rotating to the planet
        lookDirection = planet.transform.position - transform.position;
        lookAngle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.Euler(0f, 0f, lookAngle);  
    }
}

The problem is that the asteroids are attracted to the initial spawn point of the planet (0,0), it doesn’t update in real time with the movement of the planet. So if I move the planet to the corner of the screen, the asteroids are still attracted to the centre of it.

Is there a way to solve this?

Thank you very much and excuse any flagrant errors!

Hello

First of all you should use FixedUpdate instead of Update, as you manipulate physics component.

And are you sure the asteroids are rotating ? Maybe they don’t rotate so they always go toward their initial destination.
Maybe the AddForce doesn’t take into account the rotation of the asteroid.
You should try using different forceMode.
Try some Debug.Log with the differents values to see which one is wrong.