[C#] Vector2.MoveTowards Help!

I’m trying to get an object to follow my player but stop within a given distance. The following is my code, but the object doesn’t appear to be following my player, but I’m not sure why.


public Transform target;
    public float maxDistance;
    public float distance;

    PlayerController playerController;

    // Use this for initialization
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        distance = Vector2.Distance(transform.position, target.position);

        if (maxDistance <= distance)
        {
           transform.position = Vector2.MoveTowards(transform.position, target.position, Time.deltaTime * playerController.moveSpeed);
        }
    }
}

Please refer to this thread for how to post code nicely on the forums: Using code tags properly

Have you tried to put some ‘Debug.Log’ statements into your code to check the distance, if the ‘if statement’ executes, etc?
Have you checked that speed is not zero and that maxDistance is set appropriately?
Do you have any errors appearing in the console?

1 Like
 if (maxDistance <= distance)

shouldn’t it be the other way around?

 if (distance <= maxDistance)

Or is the maxDistance supposed to be the stopDistance?
In that case, the if-statement shouldn’t be flipped.

As @methos5k said, what are the values of every variable?