Search Unity

Array & Waypoint Question

Discussion in 'Scripting' started by DocJ, Oct 19, 2019.

  1. DocJ

    DocJ

    Joined:
    Dec 9, 2016
    Posts:
    98
    Hi, I'm working on a project where I think I need 2-3 arrays. All of the arrays will consist of waypoints. The Player will be mainly following the waypoints in the 1st array, but circumstances may cause the Player to be "diverted" to a waypoint in the 2nd or 3rd array.
    Is there a way to follow waypoints from multiple arrays? And if so, can the following move of the player be referenced (started) at the point he left the 1st array?

    I'm using the following to move my 2d Player:

    transform.position = Vector2.MoveTowards(transform.position, waypoints[waypointIndex].transform.position, moveSpeed * Time.deltaTime);


    Example: Car driving down the street, makes a wrong turn after the 5th block. He turns around to get back to the main street before continuing on his path.

    Thanks in advance for any help
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    You just have to think about the logic how this will happen:

    For example, here's some pseudocode:
    Code (Pseudocode):
    1. Vector2[] waypoints_L;
    2. Vector2[] waypoints_R;
    3. Vector2 currentWayPoint;
    4.  
    5. if (vehiclePosition.x < 0) {
    6.    currentWaypoint = GetWaypointL(vehiclePosition);
    7. }
    8. else if (vehiclePosition.x >= 0) {
    9.    currentWaypoint = GetWaypointR(vehiclePosition);
    10. }
    11.  
    12. transform.position = Vector2.MoveTowards(vehiclePosition, currentWaypoint, moveSpeed
    13.  * Time.deltaTime);
    You would of course have to devise a method to get the appropriate waypoint (GetWaypoint methods). You couldn't just use some incrementing counter as it would most likely point to wrong location. You could loop through the appropriate array (left or right side in my simple example) and find the waypoint that is closest to your vehicle.

    You could store the index where this closest one was and continue from that, if you need to get more waypoints on the same path.
     
    Last edited: Oct 19, 2019