[SOLVED]Move to point A, B, C, D...

Hi, iam posting this here to know if I’am even going in the right direction with this and to get litle help :slight_smile: , so I’m making this script but it doesnt work properly (yet) I will type here what the script is supposed to do and here is a gif of what it is supposed to do :

So I basically search for the nerest object in a for loop and then set nerest_pos (variable) to that index, then call Another coroutine to actually move current object to nerest object/point, the thing that I really don’t know how to do is add that nerest_pos index to a list and then check every other time it goes through the code again it checks so it doesn’t choose the same nerest_pos index again.

Here is the code:

    [SerializeField]
    private Transform[] pos;

    [SerializeField]
    private List<int> posHistIndex = new List<int>();

    [SerializeField]
    private float speed = 1;

    private int nerest_pos = 0;

    void Start () {
        StartCoroutine(movePlatform());
    }

    IEnumerator movePlatform()
    {
        while (true)
        {
            for (int i = 0; i < pos.Length; i++)
            {
                if ((Vector3.Distance(this.transform.position, pos[i].transform.position) < Vector3.Distance(this.transform.position, pos[nerest_pos].transform.position))) //get nerest platform pos - start pos
                {
                    nerest_pos = i;

                }
                else
                {

                }
            }
            if (posHistIndex.Contains(nerest_pos) == false)
                yield return StartCoroutine(moveActuly(pos[nerest_pos].transform));
                //transform.position = Vector3.MoveTowards(transform.position, pos[nerest_pos].transform.position, speed * Time.deltaTime);
            if(posHistIndex.Contains(nerest_pos) == false)
                posHistIndex.Add(nerest_pos);

            yield return null;
        }
    }

    IEnumerator moveActuly(Transform targetPos)
    {
        while (Vector3.Distance(this.transform.position, targetPos.position) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos.position, speed * Time.deltaTime);
            yield return null;
        }
    }

    private void OnGUI()
    {
        GUILayout.Label("Nerest pos: " + nerest_pos);
        GUILayout.Label("List: " + posHistIndex);
    }

Sorry for bad english and if you choose to help thanks in advance!

This is a different route:

    //List of your waypoints
    public Transform[] Waypoints;

    // How fast the object will move
    public float Speed;

    // The required distance before the object will move to the next waypoint
    public float RequiredDistance = 1.0f;

    // Current index in the waypoints array
    private int CurrentWaypointID = 0;
   
   

   
    void Update ()
    {
        //Get the distance between the object and waypoint
        float distance = Vector3.Distance(Waypoints[CurrentWaypointID].position, transform.position);

        //Moves the object toward the waypoint
        transform.position = Vector3.MoveTowards(transform.position, Waypoints[CurrentWaypointID].position, Time.deltaTime * Speed);

        //Updates the current waypoint
        if(distance <= RequiredDistance)
            CurrentWaypointID = (CurrentWaypointID + 1) % Waypoints.Length; //This you have to be careful, because if your object is going to cycle more than 2147483647 times
                                                                            //you will get an error, because it will return a negative value. Arrays do not have a negative index
    }
1 Like

You could put the waypoints into a list and then remove each one as you move to it, but…

Is there a specific reason you want to use “the nearest one” as your next waypoint? It’d be both 10x easier AND much more versatile if you just have the waypoint array in the order you want it to travel to begin with. (edit: as @SGM3 provided sample code for)

Unrelated, but: I hope that you’re only using OnGUI for debug output, and not for your actual game UI (there’s a new Unity UI system you should use for game UI).

You could store the index of the waypoint it is moving from and then when it searchs for the next point, check the new index doesn’t match the previous.

Thanks for all your replies, I’m now using the method @SGM3 mentioned works perfectly just want to know if there is any “pro” way of shortening this code

    //List of your waypoints
    public Transform[] Waypoints;

    // How fast the object will move
    public float Speed;

    // The required distance before the object will move to the next waypoint
    public float RequiredDistance = 1.0f;

    // Current index in the waypoints array
    private int CurrentWaypointID = 0;

    // If reach last index reverse direction ex: i=0,1,2,3  reverse on finish  i=2,1,0  revese on finish  i=1,2,3 ...
    public bool reverseOnFinish = false;

    // Required for "reverseOnFinish" variable to know if platform is currently moving backwards or forwards
    private bool directionForward = true;


    void Update()
    {
        //Get the distance between the object and waypoint
        float distance = Vector3.Distance(Waypoints[CurrentWaypointID].position, transform.position);

        //Moves the object toward the waypoint
        transform.position = Vector3.MoveTowards(transform.position, Waypoints[CurrentWaypointID].position, Time.deltaTime * Speed);

        //Updates the current waypoint +1 if reverseOnFinish = false
        if (reverseOnFinish == false)
        {
            if (distance <= RequiredDistance)
            {
                CurrentWaypointID += 1;
            }
        }

        //Updates the current waypoint continuously +1 or -1 depending if the value has reached maximum or minimum index
        if (directionForward && reverseOnFinish)
        {
            if (distance <= RequiredDistance)
            {
                CurrentWaypointID += 1;
            }

            if (CurrentWaypointID > Waypoints.Length - 1)
            {
                CurrentWaypointID = CurrentWaypointID - 2;
                directionForward = false;
            }
        }
        else if (directionForward == false && reverseOnFinish)
        {
            if (distance <= RequiredDistance)
            {
                CurrentWaypointID -= 1;
            }

            if (CurrentWaypointID < 0)
            {
                CurrentWaypointID = CurrentWaypointID + 2;
                directionForward = true;

            }
        }

        if (reverseOnFinish == false)
        {
            //Make sure if ID is less then 0 put it to max, if it exceeds Array length -1 put it to 0
            if (CurrentWaypointID > Waypoints.Length - 1)
            {
                CurrentWaypointID = 0;
            }
            else if (CurrentWaypointID < 0)
            {
                CurrentWaypointID = Waypoints.Length - 1;
            }
        }


    }

    private void OnGUI()
    {
        GUILayout.Label("Waypoint ID: " + CurrentWaypointID);
    }

I don’t know about ‘pro’ but definitely shorter.

    //List of your waypoints
    public Transform[] Waypoints;

    // How fast the object will move
    public float Speed;

    // The required distance before the object will move to the next waypoint
    public float RequiredDistance = 1.0f;

    // Current index in the waypoints array
    private int CurrentWaypointID = 0;

    private bool IsRerverse = false;


    void Update()
    {
        //Get the distance between the object and waypoint
        float distance = Vector3.Distance(Waypoints[CurrentWaypointID].position, transform.position);

        //Moves the object toward the waypoint
        transform.position = Vector3.MoveTowards(transform.position, Waypoints[CurrentWaypointID].position, Time.deltaTime * Speed);

        if (distance <= RequiredDistance)
        {
            if (CurrentWaypointID < Waypoints.Length - 1 && IsRerverse == false)
                CurrentWaypointID++;
            else
                IsRerverse = true;

            if (CurrentWaypointID > 0 && IsRerverse == true)
                CurrentWaypointID--;
            else
                IsRerverse = false;
        }
    }

You could shorten the nested conditionals a bit, but I don’t know if this is more readable. I typically dont like doing something like this:

bool boolean = true;
boolean = !boolean;
        if (distance <= RequiredDistance)
        {
            if (CurrentWaypointID < Waypoints.Length - 1 && IsRerverse == false)
                CurrentWaypointID++;
            else if(CurrentWaypointID > 0 && IsRerverse == true)
                CurrentWaypointID--;
            else
                IsRerverse = ! IsRerverse;
        }

With this approach, don’t hold me to it, your object may not move for one frame.