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?
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.