1设置一个比较小的阈值,当前位置和targetPos之间距离小于该阈值,可认为到达终点。
2navMeshAgent.hasPath, 当有路径的时候为true,当到达终点或初始状态为false
3navMeshAgetn.path.corners.Length获得的是当前路径拥有的顶点数。当初始状态或者到达目标点后,获得的Length数为1;当>1的时候说明还没有到达终点。
需要注意的是:
当我们通过以下任一方式设置目标点后
navMeshAgent.destination=XXX
navMeshAgent.SetDestination(XXX)
navMeshAgent.path.corners和navMeshAgent.hasPath都不会立即刷新。必须等待一帧后才会刷新。因此使用法二或者法三进行判定的时候要特别注意。
//Unity导航是否到达目的地的方法,(包括有些不可能到达的目的地)
public bool IsMoving()
{
if (!agent.enabled)
return false;
bool r = agent.pathPending ||agent.remainingDistance > agent.stoppingDistance ||agent.velocity != Vector3.zero;
r = agent.enabled ? r : false;
return r;
}
以下是官方的一个多点寻路案例 里面也有判断如何到达目标点
public class Patrol : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
void Start () {
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint() {
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}