Patrol using children waypoints

113 views Asked by At

In my game, I have multiple objects that should patrol different waypoints.

public Transform[] targets;
public float speed = 1;

private int currentTarget = 0;

IEnumerator StartMoving ()
    {   
        while (true)
        {
            float elapsedTime = 0;
            Vector3 startPos = transform.position;

            while (Vector3.Distance(transform.position, targets[currentTarget].position) > 0.05f )
            {
                transform.position = Vector3.Lerp(startPos, targets[currentTarget].position, elapsedTime/speed);
                elapsedTime += Time.deltaTime;

                yield return null;
            }
            yield return new WaitForSeconds(delay);
        }
    }

The code works fine, but for organizing reasons I would like each object to have its waypoints as children of that object, but the problem is because the waypoints are children of that object, they move with it, which results in an unwanted behavior.

Is there any workaround for this?

2

There are 2 answers

1
Everts On BEST ANSWER

You'd have to add a level of hierarchy. One parent item as container for the character and the waypoints. Then the code moves the character only.

- Container with Scripts
    - Character with mesh
    - Waypoints
        - WaypointA
        - WaypointB
        - ... 
0
Lincoln Cheng On

Well, if you really want to parent them.. you can move the waypoints in the opposite direction of the patrolling objects:

//Remember prev pos
Vector3 prevPosition = transform.position;

transform.position = Vector3.Lerp(startPos, targets[currentTarget].position, elapsedTime/speed);

//Move the waypoints in the opposite direction
foreach(Transform childWaypoint in ...)
{
  childWaypoint.position -= transform.position - prevPosition;
}    

But a better solution would be the assign an array of Vector3 for your patrolling objects..

public class Patrollers : Monobehaviour
{
  Vector3[] _waypoints;
  //..
}