1.打开寻路设置窗口
Window -> Navigation
2. 建立地形,生成寻路网格
Create Plane、 Cube ,然后在 Navigation 窗口点击 Bake 生成寻路网格。
可行通区域就出来了
3. 创建一个行走的 Actor(黑色眼镜那个) 和几个行走点(绿色球)
4. 给 Actor 添加行走
在 Actor 身上挂个 Nav Mesh Agent
5.添加个行走控制的脚本
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NavMove : MonoBehaviour
{
public NavMeshAgent agent;
public Transform[] destPos = new Transform[] { };
int currentPoint = 0;
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());
}
}
效果:
Navigation寻路-添加障碍物Obstacle
(在场景中添加障碍物,需要点Bake重新烘焙出新的 导航网格,不是运行时。
如果在运行时添加障碍物动态Bake出新的导航网格,就需要使用 Nav Mesh Obstacle)
1.创建个Cube对象 Obstacle1
2.身上挂一个组件 Nav Mesh Obstacle
3.再挂一个刚体组件 Rigidbody,并约束位置和旋转(因为不希望被撞飞)
然后可以制作成预制件Prefab,在运行时动态 Instantiate 实例化出来,寻路网格 会重新生成
效果: