Unity之尋路navigation

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


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 前言:在游戲中經常出現怪物自己會走路,人物跟隨鼠標點擊位置進行移動,那么這些功能是怎么實現的呢?通過本節內容的學習...
    Joe_Game閱讀 6,285評論 0 3
  • unity自從3.5版本之后,增加了NavMesh尋路的功能。在此之前,unity用戶只能通過第三方插件(如Ast...
    壹米玖坤閱讀 8,506評論 0 10
  • 角色控制是游戲設計中必不可少的一個設計環節,這一節我們講一講如何制作基本的角色運動控制交互邏輯。 因為是簡單實例教...
    shimmery閱讀 9,565評論 5 20
  • 一.什么是尋路? 尋路顧名思義就是:角色在到達指定地點的過程中遇到障礙物會自動避開并自行選取最短的路程進行移動。大...
    TonyWan_AR閱讀 1,151評論 0 2
  • 喜歡下雨 不喜歡雨。下雨可以靜靜自己。雨會讓人感冒
    愣啊愣閱讀 257評論 0 0