Vector3.MoveTowards Not working.

So I’m making a script that has an enemy navigate a maze using Vector3.MoveTowards and an array of transforms. The script detects if the enemy has the same x and y position as the current target point and if it does it moves towards the next one, and that part works fine. The problem is when it reaches some points on the map it refuses to change target, despite having the same x and y values as that point. I’ve been trying to figure this out for days now and I just can’t get it working. Here’s the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyNavigation : MonoBehaviour {

    public Transform[] Points;
    public float MoveSpeed;
    public int CurrentPoint;
    private bool TimeToMove;

    void Start ()  {

        CurrentPoint = 0;
        transform.position = new Vector3(Points[0].position.x, Points[0].position.y, 0);


    void Update()

        if (transform.position.x == Points[CurrentPoint].position.x & transform.position.y == Points[CurrentPoint].position.y & CurrentPoint < Points.Length & TimeToMove == false)
            CurrentPoint = CurrentPoint + 1;
            TimeToMove = true;
            Debug.Log("Reached Point...");

        transform.position = Vector3.MoveTowards(transform.position, Points[CurrentPoint].position, MoveSpeed * Time.deltaTime);


    public IEnumerator WaitForBool ()
        yield return new WaitForSeconds(0.2f);
        TimeToMove = false;


Thanks in advance. =)


Due to floating-point error and Time.deltaTime differences if lagging, the positions may never be truly equal, just off by like .00001 or something. You should use a buffer so it will return true if within a certain area, not exactly on top of the point.


It’s good practice to use conditional AND operator (&&) instead of binary AND (&).


float buffer = .1f; //If within .1 meters, it will return true

if ( 
TimeToMove == false  /*you should probably put these ones first so it won't cause errors*/
&& CurrentPoint < Points.Length
&& Mathf.Abs(transform.position.x - Points[CurrentPoint].position.x) < buffer
&& Mathf.Abs(transform.position.y - Points[CurrentPoint].position.y) < buffer

Hope that solves your stuff,