導航網格navigation mesh)係電子遊戲入面一種常用嚟控制 AI 移動嘅做法。一個導航網格有若干個二維嘅多邊形定義環境入面有邊啲平面係個 AI 可以行嘅,網格以外嘅空間就係個 AI 唔去得嘅地方[1]

例子碼 編輯

以下呢段 Unity 入面嘅 C# 碼教一個物件按導航網格移動嘅例子碼:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class NavTesting : MonoBehaviour
{
    [SerializeField]
    Transform _destination; // 定義有一個位置叫 destination,喺 Unity 當中,個位置嘅坐標值可以喺 C# 以外嘅介面定義。
    NavMeshAgent _navMeshAgent; // 有一個物體係移動緊嗰件物件。

    void Start()
    {
        _navMeshAgent = this.GetComponent<NavMeshAgent>(); // 要移動嗰件物件係呢段碼 attach 住嗰件...
        if(_navMeshAgent == null) // if 段碼冇 attach 住任何物件,出 error 信息...
        {
            Debug.LogError("The nav mesh agent component is not attached to " + gameObject.name); 

        }
        else
        {
            SetDestination(); // ... 否則就做 SetDestination
        }

    }
    private void SetDestination()
    {
        if (_destination != null) // if destination 有數值...
        {
            Vector3 targetVector = _destination.transform.position; // targetVector 係一個有三個數值嘅向量,設 targetVector 係 destination 嘅位置
            _navMeshAgent.SetDestination(targetVector); 
        }
    }
}

睇埋 編輯

編輯

  1. Snook, Greg (2000). "Simplified 3D Movement and Pathfinding Using Navigation Meshes". In DeLoura, Mark (ed.). Game Programming Gems. Charles River Media. pp. 288–304.