游戏引擎 / 系统课时
处理追击失败和路径重算
处理追击失败和路径重算
敌人追击移动中的玩家时,可能遇到目标不可达、路径计算失败或卡在拐角的情况。本课为 Unity 6 的 NavMeshAgent 加上状态检查、限频重算和失败回退,让敌人能恢复正常追击,也能在确实无路可走时停止消耗寻路预算。
学习目标
- 区分路径尚在计算、部分可达、无效路径与实际移动停滞。
- 使用时间间隔、位移阈值和失败次数限制
SetDestination调用。 - 在断路、动态目标与狭窄拐角场景中验证恢复行为。
先判断路径是否真的失败
以下 API 适用于 Unity 6(6000.x)的 UnityEngine.AI.NavMeshAgent。SetDestination 返回 true 只代表成功提交目标请求,不代表路径已经算出,更不代表一定可达。应先等待 pathPending 结束,再读 pathStatus。
| 检查项 | 观察结果 | 处理 |
|---|---|---|
isOnNavMesh |
false |
代理未绑定导航网格,停止追击并检查出生位置或烘焙 |
pathPending |
true |
等待计算完成;示例超过 2 秒按超时处理 |
pathStatus |
PathComplete |
路径能抵达目标点,可监测实际移动 |
pathStatus |
PathPartial |
只能抵达部分路径的末端,进入受限重试 |
pathStatus |
PathInvalid |
路径无效,进入受限重试 |
remainingDistance |
Infinity |
剩余距离未知,不能当作已到达 |
停滞与无路可走不是同一问题。例如路径为 PathComplete,敌人却在墙角被其他代理挤住,此时应该观察实际位移;而 PathPartial 不需要等敌人走到断点才知道无法到达。
给重算设置预算和出口
采用一组能直接调试的初始参数:每 0.2 秒检查一次;追击目标距上次提交位置移动至少 1 米,且两次请求相隔至少 0.5 秒,才更新目标点。若已有完整路径但 1.5 秒内前进不足 0.15 米,则判为停滞;路径请求超过 2 秒仍在计算,也算一次失败。
失败第 1 次等待 1 秒,第 2 次等待 2 秒,再尝试;第 3 次失败放弃追击,交给上层 AI 切换搜索或巡逻。成功走出至少 0.15 米后将失败计数清零,避免偶发拥堵消耗整个重试预算。

autoRepath 可以在现有路径失效时尝试重新寻路,但不能替代对移动目标的定期更新,也不能替代停滞超时与放弃条件。
实现可恢复的追击组件
新建 ReliableEnemyChase.cs,挂到带 NavMeshAgent 的敌人根节点。以下是完整的 Unity MonoBehaviour 示例;场景需要先烘焙导航网格,且在 Inspector 中指定 Target。
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public sealed class ReliableEnemyChase : MonoBehaviour
{
[SerializeField, Min(0.05f)] private float checkInterval = 0.2f;
[SerializeField, Min(0.1f)] private float repathInterval = 0.5f;
[SerializeField, Min(0.1f)] private float targetMoveThreshold = 1f;
[SerializeField, Min(0.1f)] private float stuckSeconds = 1.5f;
[SerializeField, Min(0.01f)] private float minProgress = 0.15f;
[SerializeField, Min(1)] private int maxFailures = 3;
[SerializeField] private Transform target;
private NavMeshAgent agent;
private Vector3 lastTarget;
private Vector3 progressPosition;
private float lastProgressTime;
private float nextCheckTime;
private float nextRequestTime;
private float requestStartTime;
private int failures;
private bool waitingForPath;
private bool arrived;
private bool abandoned;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
agent.autoRepath = true;
progressPosition = transform.position;
lastProgressTime = Time.time;
}
private void Update()
{
if (abandoned || Time.time < nextCheckTime) return;
nextCheckTime = Time.time + checkInterval;
if (target == null || !agent.isOnNavMesh)
{
Abandon("目标缺失或代理不在 NavMesh 上");
return;
}
// 必须在路径计算完成后才能判读最终路径状态。
if (waitingForPath)
{
if (agent.pathPending)
{
if (Time.time - requestStartTime >= 2f) Fail("路径计算超时");
return;
}
waitingForPath = false;
if (!agent.hasPath || agent.pathStatus != NavMeshPathStatus.PathComplete)
{
Fail("路径状态:" + agent.pathStatus);
return;
}
}
if (arrived)
{
if (Vector3.Distance(target.position, lastTarget) >= targetMoveThreshold)
RequestPath();
return;
}
if (agent.hasPath)
{
if (agent.pathStatus != NavMeshPathStatus.PathComplete)
{
Fail("路径已失效");
return;
}
if (!float.IsInfinity(agent.remainingDistance) &&
agent.remainingDistance <= agent.stoppingDistance + 0.15f)
{
arrived = true;
failures = 0;
return;
}
// 不将跨越 NavMesh Link 的等待误判为普通墙角卡住。
if (!agent.isOnOffMeshLink)
{
if (Vector3.Distance(agent.nextPosition, progressPosition) >= minProgress)
{
progressPosition = agent.nextPosition;
lastProgressTime = Time.time;
failures = 0;
}
else if (Time.time - lastProgressTime >= stuckSeconds)
{
Fail("持续停滞");
return;
}
}
else
{
progressPosition = agent.nextPosition;
lastProgressTime = Time.time;
}
}
if (!agent.hasPath || agent.isPathStale ||
Vector3.Distance(target.position, lastTarget) >= targetMoveThreshold)
RequestPath();
}
private void RequestPath()
{
if (Time.time < nextRequestTime) return;
nextRequestTime = Time.time + repathInterval;
// 小范围采样限制远距离吸附,可达性仍须等待路径结果。
if (!NavMesh.SamplePosition(target.position, out NavMeshHit hit, 1f, agent.areaMask) ||
!agent.SetDestination(hit.position))
{
Fail("目标点不可用或路径请求失败");
return;
}
if (!agent.hasPath)
{
progressPosition = agent.nextPosition;
lastProgressTime = Time.time;
}
lastTarget = target.position;
requestStartTime = Time.time;
waitingForPath = true;
arrived = false;
agent.isStopped = false;
}
private void Fail(string reason)
{
waitingForPath = false;
arrived = false;
agent.isStopped = true;
agent.ResetPath();
failures++;
if (failures >= maxFailures)
{
Abandon(reason);
return;
}
float delay = Mathf.Pow(2f, failures - 1);
nextRequestTime = Time.time + delay;
progressPosition = agent.nextPosition;
lastProgressTime = Time.time;
Debug.LogWarning($"[{name}] 重试 {failures}/{maxFailures}:{reason},等待 {delay:0.0}s", this);
}
private void Abandon(string reason)
{
abandoned = true;
if (agent.isOnNavMesh)
{
agent.isStopped = true;
agent.ResetPath();
}
Debug.LogWarning($"[{name}] 放弃追击:{reason}", this);
// 接入项目时在这里通知 AI 状态机返回搜索或巡逻。
}
public void ResumeChase(Transform newTarget)
{
// AI 再次发现目标时,清除旧路径与本轮失败预算。
target = newTarget;
abandoned = false;
arrived = false;
waitingForPath = false;
failures = 0;
nextCheckTime = 0f;
nextRequestTime = 0f;
progressPosition = agent.isOnNavMesh ? agent.nextPosition : transform.position;
lastProgressTime = Time.time;
if (agent.isOnNavMesh) agent.ResetPath();
}
}预期结果:若名为 Enemy 的对象连续三次得到 PathPartial,Console 中的日志正文如下;实际场景也可能得到 PathInvalid,两者都会触发同一回退策略。
[Enemy] 重试 1/3:路径状态:PathPartial,等待 1.0s
[Enemy] 重试 2/3:路径状态:PathPartial,等待 2.0s
[Enemy] 放弃追击:路径状态:PathPartial代码用 nextPosition 观察导航代理的真实模拟位移,适合 NavMeshAgent 主导移动的角色。如果 Animator 根运动另行控制 Transform,需要先正确同步代理与角色位置,否则会产生虚假的停滞报警。
接线与三组场景验收
- 在 Unity 6 中确认 AI Navigation 已安装、场景已有可行走的 NavMesh;给敌人添加
NavMeshAgent和脚本,把玩家 Transform 拖到Target。 - 先使用
Speed = 3.5、Acceleration = 8、Angular Speed = 360、Stopping Distance = 1.5(米制项目),检查敌人初始脚底确实贴在可行走区域。 - 将玩家沿墙转弯移动超过 1 米:敌人应绕过墙体调整路径,不会每帧重复提交新目标。
- 将玩家放到与敌人不连通的导航岛:应看到部分或无效路径、受限重试以及最后放弃追击。
- 在窄门口用其他代理暂时堵路:停滞超过 1.5 秒触发重算;解除拥堵并实际前进 0.15 米后,失败计数应清零。
避免把正常等待误判为故障
路径还在 pathPending 时不检查 remainingDistance 是否到达;它可能是无穷大。靠近目标且距离不超过 Stopping Distance + 0.15 米时,停滞计时应暂停;否则敌人成功停下也会被重试逻辑打断。
还有两个需要单独处理的边界:一是脚本中的 abandoned 只表示停止追击,接入完整 AI 时应由状态机负责切换搜索、巡逻以及重新发现目标后的状态复位;二是手动驱动的 NavMesh Link 需要自己的超时处理,不能仅因为导航代理在链接上而永久跳过异常检测。重新发现玩家时,状态机可调用 ResumeChase(playerTransform) 清除上轮失败记录;切换巡逻时则应由巡逻模块接管目的地。
验收时优先观察每次 SetDestination 的请求次数、pathStatus 与位置变化,而不是只看敌人最后能否追上玩家。这三项分别对应性能、可达性与停滞原因,能把不断重算的问题定位到具体环节。