使用儿童巡逻 waypoints

Patrol using children waypoints

在我的游戏中,我有多个应该巡逻不同的对象 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);
        }
    }

代码工作正常,但出于组织原因,我希望每个对象都将其 waypoints 作为该对象的子对象,但问题是因为 waypoints 是该对象的子对象,他们会随之移动,这会导致不良行为。

有什么解决方法吗?

您必须添加一个层次结构。一个父项作为角色和 waypoints 的容器。然后代码只移动字符。

- Container with Scripts
    - Character with mesh
    - Waypoints
        - WaypointA
        - WaypointB
        - ... 

好吧,如果你真的想要抚养他们..你可以将waypoints移动到与巡逻对象相反的方向:

//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;
}    

但更好的解决方案是为您的巡逻对象分配一个 Vector3 数组..

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