- 寻路模块,Navigation
- 和ue4中的很相似 http://blog.csdn.net/yangxuan0261/article/details/50272423
效果图
1. 建立地形,生成寻路网格
随便 Create Plane、 Cube ,选中这两个物体的状态下
打开寻路设置窗口 Window -> Navigation -> Object , 勾选 Navigation Static,
Navigation 窗口点击 Bake 生成寻路网格。寻路数据自动生成在 场景同名文件夹下的 NavMesh.asset
这种静态的增加障碍物,动态增加在这里 http://blog.csdn.net/yangxuan0261/article/details/52821833
Bake 之后 物体的变为 Navigation Static 状态
可行通区域就出来了, 边界值可以通过 Bake -> Agent Radius 中设置大小, 最小是 0.01, 越小bake的速度就越慢
自定义地形
地形可以 3d软件如 3dsmax 中构建一个自定义的 地形mesh
然后导出 fbx 给 unity, bake 寻路数据
效果图
2. 创建一个行走的 Actor(黑色眼镜那个) 和几个行走点(绿色球)
3. 给 Actor 添加行走
在 Actor 身上挂个 Nav Mesh Agent
添加个行走控制的脚本
NavMove.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class NavMove : MonoBehaviour { public NavMeshAgent agent; public Transform[] destPos = new Transform[] { }; int currentPoint = 0; // Use this for initialization void Start() { agent.Stop(); StartCoroutine(Move()); } IEnumerator Move() { //enable agent updates agent.Resume(); agent.updateRotation = true; agent.SetDestination(destPos[currentPoint].position); yield return StartCoroutine(WaitForDestination()); StartCoroutine(NextWaypoint()); } IEnumerator WaitForDestination() { yield return new WaitForEndOfFrame(); while (agent.pathPending) yield return null; yield return new WaitForEndOfFrame(); float remain = agent.remainingDistance; while (remain == Mathf.Infinity || remain - agent.stoppingDistance > float.Epsilon || agent.pathStatus != NavMeshPathStatus.PathComplete) { remain = agent.remainingDistance; yield return null; } Debug.LogFormat("--- PathComplete to pos:{0}", currentPoint); } IEnumerator NextWaypoint() { currentPoint++; currentPoint = currentPoint % destPos.Length; Transform next = destPos[currentPoint]; agent.SetDestination(next.position); yield return StartCoroutine(WaitForDestination()); StartCoroutine(NextWaypoint()); } }
这种使用 Coroutine 移动到目的点 的方式是在 Simple Waypoint System 插件中的 navMove.cs 中看到的。利用 Coroutine 来达到 分帧执行 使得代码变得非常简洁。
done
高级设置
agent 指定 layer 行走区域
添加 指定layer: WalkArea
bake 寻路数据时, 指定layer 为 WalkArea
agent 中指定行走的区域为 WalkArea