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 實例化出來,尋路網格 會重新生成
效果: