使用儿童航路点进行巡逻

时间:2016-12-22 02:23:53

标签: unity3d position children

在我的游戏中,我有多个对象应该巡逻不同的航点。

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

代码工作正常,但出于组织原因,我希望每个对象都将其路点作为该对象的子节点,但问题是因为路点是该对象的子节点,它们随之移动,从而导致不需要的行为。

这有什么解决方法吗?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

好吧,如果你真的想要让他们成为父母......你可以沿着巡逻对象的相反方向移动路标:

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