U
Unity
星辰学院
首页
课程表
章节导览
第 1 课
返回主站
首页
/
第 15 章 · 寻路与导航
/
第 256 课
LESSON 256 · 寻路与导航
AI 巡逻路径系统(Waypoint)
巡逻系统完成。下一课做群组 AI。
⏱ 约 14 分钟
📊 难度:
入门
🗂 第 15 章 · 寻路与导航
📍 第 256 / 300 课
课程进度
256 / 300
🎯
本节学习目标
实现路径点巡逻
实现巡逻停留
实现随机巡逻
🚀
课程导读
“守卫来回巡逻”是 AI 常态。本课用 Waypoint(路径点)实现多种巡逻方式。
◆
路径点巡逻
按点走、到点停。
【方式1 手动路径点】场景里放几个空对象作路径点(Waypoint1/2/3)。
【巡逻脚本】
public Transform[] waypoints;
public float speed = 3f;
public float waitTime = 1f;
private NavMeshAgent agent;
private int current = 0;
void Start() { agent = GetComponent<NavMeshAgent>(); GoNext(); }
void GoNext() { agent.SetDestination(waypoints[current].position); }
void Update() {
if (!agent.pathPending && agent.remainingDistance < 1f) {
current = (current + 1) % waypoints.Length;
StartCoroutine(WaitAndGo());
}
}
IEnumerator WaitAndGo() {
agent.isStopped = true;
yield return new WaitForSeconds(waitTime);
agent.isStopped = false;
GoNext();
}
【说明】到点停 waitTime 再去下一个(循环)。
【可视化】路径点可加 Gizmo 画出连线(进阶)。
【测试】AI 沿路径点循环巡逻。
【完成】“巡逻路线”通了!
💡
Waypoint 巡逻 = 路径点数组 + 按序 SetDestination + 到点停留。循环走。
◆
随机与条件巡逻
更多巡逻花样。
【随机巡逻】从路径点随机选下一个:
int next = Random.Range(0, waypoints.Length);
【或】在 NavMesh 上随机找可走点:
RandomPointOnNavMesh(origin, range, out pos);
【实现】RandomPointOnNavMesh 用 NavMesh.SamplePosition:
public static bool RandomPoint(Vector3 center, float range, out Vector3 result) {
for (int i = 0; i < 30; i++) {
Vector3 random = center + Random.insideUnitSphere * range;
NavMeshHit hit;
if (NavMesh.SamplePosition(random, out hit, 1f, NavMesh.AllAreas)) { result = hit.position; return true; }
}
result = Vector3.zero; return false;
}
【视野切换】巡逻与追击结合(第 211/235 课):
发现玩家 → SetDestination(player)(追);丢失 → 回巡逻。
【巡逻点绑定敌人】每个敌人自己的路径点数组(可配置)。
【测试】随机巡逻、发现玩家追击、丢失回巡逻。
【完成】AI 巡逻“专业”了!
✅
巡逻三式:固定路线(Waypoint 循环)、随机点(SamplePosition)、条件切换(视野追/巡)。
⚠
常见错误与排查
⛔
错误:
AI 巡逻时卡在某点?
原因:
路径点不可达或判断条件不满足
解决:
确认路径点在 NavMesh 上可达;remainingDistance 阈值合适;isStopped 正确恢复。
★
动手练习
课后小任务(做出来才算真的学会)
做固定路线巡逻
做随机点巡逻
整合巡逻与追击
✓
本节小结
巡逻系统完成。下一课做群组 AI。
标记为已完成
完成打卡后,主站会实时更新你的学习进度 🎯
← 上一课
Off-Mesh Link 跳跃连接
下一课 →
群组 AI 与避让
↑