Unity3d 中的 A*尋路

這篇文章翻譯自Unity 4.x Game AI Programming這本書第七章

在本章中,我們將在Unity3D環境中使用C#實現A*算法.儘管有很多其他算法,像Dijkstra算法,但A*算法以其簡單性和有效性而廣泛的應用於遊戲和交互式應用中.我們之前在第一章AI介紹中短暫的涉及到了該算法.不過現在我們從實現的角度來再次複習該算法.

A*算法複習

在我們進入下一部分實現A*之前,我們再次複習一下A*算法.首先,我們將需要用可遍歷的數據結構來表示地圖.儘管可能有很多結構可實現,在這個例子中我們將使用2D格子數組.我們稍後將實現GridManager類來處理這個地圖信息.我們的類GridManager將記錄一系列的Node對象,這些Node對象纔是2D格子的主題.所以我們需要實現Node類來處理一些東西,比如節點類型,他是是一個可通行的節點還是障礙物,穿過節點的代價和到達目標節點的代價等等.

我們將用兩個變量來存儲已經處理過的節點和我們要處理的節點.我們分別稱他們爲關閉列表和開放列表.我們將在PriorityQueue類裏面實現該列表類型.我們現在看看它:

  1. 首先,從開始節點開始,將開始節點放入開放列表中.
  2. 只要開放列表中有節點,我們將進行一下過程.
  3. 從開放列表中選擇第一個節點並將其作爲當前節點(我們將在代碼結束時提到它,這假定我們已經對開放列表排好序且第一個節點有最小代價值).
  4. 獲得這個當前節點的鄰近節點,它們不是障礙物,像一堵牆或者不能穿越的峽谷一樣.
  5. 對於每一個鄰近節點,檢查該鄰近節點是否已在關閉列表中.如果不在,我們將爲這個鄰近節點計算所有代價值(F),計算時使用下面公式:F = G + H,在前面的式子中,G是從上一個節點到這個節點的代價總和,H是從當前節點到目的節點的代價總和.
  6. 將代價數據存儲在鄰近節點中,並且將當前節點保存爲該鄰近節點的父節點.之後我們將使用這個父節點數據來追蹤實際路徑.
  7. 將鄰近節點存儲在開放列表中.根據到他目標節點的代價總和,以升序排列開放列表.
  8. 如果沒有鄰近節點需要處理,將當前節點放入關閉列表並將其從開放列表中移除.
  9. 返回第二步
一旦你完成了這個過程,你的當前節點將在目標節點的位置,但只有當存在一條從開始節點到目標節點的無障礙路徑.如果當前節點不在目標節點,那就沒有從目標節點到當前節點的路徑.如果存在一條正確的路徑我們現在所能做的就是從當前節點的父節點開始追溯,直到我們再次到達開始節點.這樣我們得到一個路徑列表,其中的節點都是我們在尋路過程中選擇的,並且該列表從目標節點排列到開始節點.之後我們翻轉這個路徑列表,因爲我們需要知道從開始節點到目標節點的路徑.

這就是我們將在Unity3D中使用C#實現的算法概覽.所以,搞起吧.

實現

我們將實現我們之前提到過的基礎類比如Node類,GridManager類和PriorityQueue類.我們將在後續的主AStar類裏面使用它們.

Node

Node類將處理代表我們地圖的2D格子中其中的每個格子對象,一下是Node.cs文件.
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System;  
  4.   
  5. public class Node : IComparable {  
  6.     public float nodeTotalCost;  
  7.     public float estimatedCost;  
  8.     public bool bObstacle;  
  9.     public Node parent;  
  10.     public Vector3 position;  
  11.       
  12.     public Node() {  
  13.         this.estimatedCost = 0.0f;  
  14.         this.nodeTotalCost = 1.0f;  
  15.         this.bObstacle = false;  
  16.         this.parent = null;  
  17.     }  
  18.       
  19.     public Node(Vector3 pos) {  
  20.         this.estimatedCost = 0.0f;  
  21.         this.nodeTotalCost = 1.0f;  
  22.         this.bObstacle = false;  
  23.         this.parent = null;  
  24.         this.position = pos;  
  25.     }  
  26.       
  27.     public void MarkAsObstacle() {  
  28.         this.bObstacle = true;  
  29.     }  
Node類有其屬性,比如代價值(G和H),標識其是否是障礙物的標記,和其位置和父節點. nodeTotalCost是G,它是從開始節點到當前節點的代價值,estimatedCost是H,它是從當前節點到目標節點的估計值.我們也有兩個簡單的構造方法和一個包裝方法來設置該節點是否爲障礙物.之後我們實現如下面代碼所示的CompareTo方法:
  1. public int CompareTo(object obj)  
  2. {  
  3.     Node node = (Node) obj;  
  4.     //Negative value means object comes before this in the sort order.  
  5.     if (this.estimatedCost < node.estimatedCost)  
  6.             return -1;  
  7.     //Positive value means object comes after this in the sort order.  
  8.     if (this.estimatedCost > node.estimatedCost)  
  9.             return 1;  
  10.     return 0;  
  11. }  
這個方法很重要.我們的Node類繼承自ICompare因爲我們想要重寫這個CompareTo方法.如果你能想起我們在之前算法部分討論的東西,你會注意到我們需要根據所有預估代價值來排序我們的Node數組.ArrayList類型有個叫Sort.Sort的方法,該方法只是從列表中的對象(在本例中是Node對象)查找對象內部實現的CompareTo方法.所以,我們實現這個方法並根據estimatedCost值來排序Node對象.你可以從以下資源中瞭解到更多關於.Net framework的該特色.

PriorityQueue

PriorityQueue是一個簡短的類,使得ArrayList處理節點變得容易些,PriorityQueue.cs展示如下:
  1. using UnityEngine;  
  2. using System.Collections;  
  3. public class PriorityQueue {  
  4.     private ArrayList nodes = new ArrayList();  
  5.       
  6.     public int Length {  
  7.         get { return this.nodes.Count; }  
  8.     }  
  9.       
  10.     public bool Contains(object node) {  
  11.         return this.nodes.Contains(node);  
  12.     }  
  13.       
  14.     public Node First() {  
  15.         if (this.nodes.Count > 0) {  
  16.             return (Node)this.nodes[0];  
  17.         }  
  18.                 return null;  
  19.     }  
  20.       
  21.     public void Push(Node node) {  
  22.         this.nodes.Add(node);  
  23.         this.nodes.Sort();  
  24.     }  
  25.       
  26.     public void Remove(Node node) {  
  27.         this.nodes.Remove(node);  
  28.         //Ensure the list is sorted  
  29.         this.nodes.Sort();  
  30.     }  
  31. }  
上面的代碼很好理解.需要注意的一點是從節點的ArrayList添加或者刪除節點後我們調用了Sort方法.這將調用Node對象的CompareTo方法,且將使用estimatedCost值來排序節點.

GridManager

GridManager類處理所有代表地圖的格子的屬性.我們將GridManager設置單例,因爲我們只需要一個對象來表示地圖.GridManager.cs代碼如下:
  1. using UnityEngine;  
  2. using System.Collections;  
  3. public class GridManager : MonoBehaviour {  
  4.     private static GridManager s_Instance = null;  
  5.     public static GridManager instance {  
  6.         get {  
  7.             if (s_Instance == null) {  
  8.                 s_Instance = FindObjectOfType(typeof(GridManager))   
  9.                         as GridManager;  
  10.                 if (s_Instance == null)  
  11.                     Debug.Log("Could not locate a GridManager " +  
  12.                             "object. \n You have to have exactly " +  
  13.                             "one GridManager in the scene.");  
  14.             }  
  15.             return s_Instance;  
  16.         }  
  17.     }  
我們在場景中尋找GridManager對象,如果找到我們將其保存在s_Instance靜態變量裏.
  1. public int numOfRows;    
  2. public int numOfColumns;    
  3. public float gridCellSize;    
  4. public bool showGrid = true;    
  5. public bool showObstacleBlocks = true;    
  6. private Vector3 origin = new Vector3();    
  7. private GameObject[] obstacleList;    
  8. public Node[,] nodes { getset; }    
  9. public Vector3 Origin {    
  10.     get { return origin; }  
  11. }  
緊接着我們聲明所有的變量;我們需要表示我們的地圖,像地圖行數和列數,每個格子的大小,以及一些布爾值來形象化(visualize)格子與障礙物.此外還要向下面的代碼一樣保存格子上存在的節點:
  1. void Awake() {  
  2.     obstacleList = GameObject.FindGameObjectsWithTag("Obstacle");  
  3.     CalculateObstacles();  
  4. }  
  5. // Find all the obstacles on the map  
  6. void CalculateObstacles() {  
  7.     nodes = new Node[numOfColumns, numOfRows];  
  8.     int index = 0;  
  9.     for (int i = 0; i < numOfColumns; i++) {  
  10.         for (int j = 0; j < numOfRows; j++) {  
  11.             Vector3 cellPos = GetGridCellCenter(index);  
  12.             Node node = new Node(cellPos);  
  13.             nodes[i, j] = node;  
  14.             index++;  
  15.         }  
  16.     }  
  17.     if (obstacleList != null && obstacleList.Length > 0) {  
  18.         //For each obstacle found on the map, record it in our list  
  19.         foreach (GameObject data in obstacleList) {  
  20.             int indexCell = GetGridIndex(data.transform.position);  
  21.             int col = GetColumn(indexCell);  
  22.             int row = GetRow(indexCell);  
  23.             nodes[row, col].MarkAsObstacle();  
  24.         }  
  25.     }  
  26. }  
我們查找所有標籤爲Obstacle的遊戲對象(game objects)並將其保存在我們的obstacleList屬性中.之後在CalculateObstacles方法中設置我們節點的2D數組.首先,我們創建具有默認屬性的普通節點屬性.在這之後我們查看obstacleList.將其位置轉換成行,列數據(即節點是第幾行第幾列)並更新對應索引處的節點爲障礙物.

GridManager有一些輔助方法來遍歷格子並得到對應格子的對局.以下是其中一些函數(附有簡短說明以闡述它們的是做什麼的).實現很簡單,所以我們不會過多探究其細節.
GetGridCellCenter方法從格子索引中返回世界座標系中的格子位置,代碼如下:
  1. public Vector3 GetGridCellCenter(int index) {  
  2.     Vector3 cellPosition = GetGridCellPosition(index);  
  3.     cellPosition.x += (gridCellSize / 2.0f);  
  4.     cellPosition.z += (gridCellSize / 2.0f);  
  5.     return cellPosition;  
  6. }  
  7. public Vector3 GetGridCellPosition(int index) {  
  8.     int row = GetRow(index);  
  9.     int col = GetColumn(index);  
  10.     float xPosInGrid = col * gridCellSize;  
  11.     float zPosInGrid = row * gridCellSize;  
  12.     return Origin + new Vector3(xPosInGrid, 0.0f, zPosInGrid);  
  13. }  
GetGridIndex方法從給定位置返回格子中的格子索引:
  1. public int GetGridIndex(Vector3 pos) {  
  2.     if (!IsInBounds(pos)) {  
  3.         return -1;  
  4.     }  
  5.     pos -= Origin;  
  6.     int col = (int)(pos.x / gridCellSize);  
  7.     int row = (int)(pos.z / gridCellSize);  
  8.     return (row * numOfColumns + col);  
  9. }  
  10. public bool IsInBounds(Vector3 pos) {  
  11.     float width = numOfColumns * gridCellSize;  
  12.     float height = numOfRows* gridCellSize;  
  13.     return (pos.x >= Origin.x &&  pos.x <= Origin.x + width &&  
  14.             pos.x <= Origin.z + height && pos.z >= Origin.z);  
  15. }  
GetRow和GetColumn方法分別從給定索引返回格子的行數和列數.
  1. public int GetRow(int index) {  
  2.     int row = index / numOfColumns;  
  3.     return row;  
  4. }  
  5. public int GetColumn(int index) {  
  6.     int col = index % numOfColumns;  
  7.     return col;  
  8. }  
另外一個重要的方法是GetNeighbours,它被AStar類用於檢索特定節點的鄰接點.
  1. public void GetNeighbours(Node node, ArrayList neighbors) {  
  2.     Vector3 neighborPos = node.position;  
  3.     int neighborIndex = GetGridIndex(neighborPos);  
  4.     int row = GetRow(neighborIndex);  
  5.     int column = GetColumn(neighborIndex);  
  6.     //Bottom  
  7.     int leftNodeRow = row - 1;  
  8.     int leftNodeColumn = column;  
  9.     AssignNeighbour(leftNodeRow, leftNodeColumn, neighbors);  
  10.     //Top  
  11.     leftNodeRow = row + 1;  
  12.     leftNodeColumn = column;  
  13.     AssignNeighbour(leftNodeRow, leftNodeColumn, neighbors);  
  14.     //Right  
  15.     leftNodeRow = row;  
  16.     leftNodeColumn = column + 1;  
  17.     AssignNeighbour(leftNodeRow, leftNodeColumn, neighbors);  
  18.     //Left  
  19.     leftNodeRow = row;  
  20.     leftNodeColumn = column - 1;  
  21.     AssignNeighbour(leftNodeRow, leftNodeColumn, neighbors);  
  22. }  
  23.   
  24. void AssignNeighbour(int row, int column, ArrayList neighbors) {  
  25.     if (row != -1 && column != -1 &&   
  26.         row < numOfRows && column < numOfColumns) {  
  27.       Node nodeToAdd = nodes[row, column];  
  28.       if (!nodeToAdd.bObstacle) {  
  29.         neighbors.Add(nodeToAdd);  
  30.       }  
  31.     }  
  32.   }  
首先,我們在當前節點的左右上下四個方向檢索其鄰接節點.之後,在AssignNeighbour方法中,我們檢查鄰接節點看其是否爲障礙物.如果不是我們將其添加neighbours中.緊接着的方法是一個調試輔助方法用於形象化(visualize)格子和障礙物.
  1. void OnDrawGizmos() {  
  2.         if (showGrid) {  
  3.             DebugDrawGrid(transform.position, numOfRows, numOfColumns,   
  4.                     gridCellSize, Color.blue);  
  5.         }  
  6.         Gizmos.DrawSphere(transform.position, 0.5f);  
  7.         if (showObstacleBlocks) {  
  8.             Vector3 cellSize = new Vector3(gridCellSize, 1.0f,  
  9.                 gridCellSize);  
  10.             if (obstacleList != null && obstacleList.Length > 0) {  
  11.                 foreach (GameObject data in obstacleList) {  
  12.                     Gizmos.DrawCube(GetGridCellCenter(  
  13.                             GetGridIndex(data.transform.position)), cellSize);  
  14.                 }  
  15.             }  
  16.         }  
  17.     }  
  18.     public void DebugDrawGrid(Vector3 origin, int numRows, int  
  19.         numCols,float cellSize, Color color) {  
  20.         float width = (numCols * cellSize);  
  21.         float height = (numRows * cellSize);  
  22.         // Draw the horizontal grid lines  
  23.         for (int i = 0; i < numRows + 1; i++) {  
  24.             Vector3 startPos = origin + i * cellSize * new Vector3(0.0f,  
  25.                 0.0f, 1.0f);  
  26.             Vector3 endPos = startPos + width * new Vector3(1.0f, 0.0f,  
  27.                 0.0f);  
  28.             Debug.DrawLine(startPos, endPos, color);  
  29.         }  
  30.             // Draw the vertial grid lines  
  31.         for (int i = 0; i < numCols + 1; i++) {  
  32.             Vector3 startPos = origin + i * cellSize * new Vector3(1.0f,  
  33.                 0.0f, 0.0f);  
  34.             Vector3 endPos = startPos + height * new Vector3(0.0f, 0.0f,  
  35.                 1.0f);  
  36.             Debug.DrawLine(startPos, endPos, color);  
  37.         }  
  38.     }  
  39. }  
Gizmos在編輯器場景視圖中可以用於繪製可視化的調試並建立輔助.OnDrawGizmos在每一幀都會被引擎調用.所以,如果調試標識showGrid和showObstacleBlocks被勾選我們就是用線條繪製格子使用立方體繪製障礙物.我們就不講DebugDrawGrid這個簡單的方法了.
注意:你可以從Unity3D參考文檔瞭解到更多有關gizmos的資料

AStar

類AStar是將要使用我們目前所實現的類的主類.如果你想複習這的話,你可以返回算法部分.如下面AStar.cs代碼所示,我們先聲明我們的openList和closedList,它們都是PriorityQueue類型.

  1. using UnityEngine;  
  2. using System.Collections;  
  3. public class AStar {  
  4.     public static PriorityQueue closedList, openList;  
接下來我們實現一個叫HeursticEstimatedCost方法來計算兩個節點之間的代價值.計算很簡單.我們只是通過兩個節點的位置向量相減得到方向向量.結果向量的長度便告知了我們從當前節點到目標節點的直線距離.

  1. private static float HeuristicEstimateCost(Node curNode,   
  2.         Node goalNode) {  
  3.     Vector3 vecCost = curNode.position - goalNode.position;  
  4.     return vecCost.magnitude;  
  5. }  
接下來使我們主要的FindPath方法:

  1. public static ArrayList FindPath(Node start, Node goal) {  
  2.     openList = new PriorityQueue();  
  3.     openList.Push(start);  
  4.     start.nodeTotalCost = 0.0f;  
  5.     start.estimatedCost = HeuristicEstimateCost(start, goal);  
  6.     closedList = new PriorityQueue();  
  7.     Node node = null;  
我們初始化開放和關閉列表.從開始節點開始,我們將其放入開放列表.之後我們便開始處理我們的開放列表.

  1.     while (openList.Length != 0) {  
  2.         node = openList.First();  
  3.         //Check if the current node is the goal node  
  4.         if (node.position == goal.position) {  
  5.             return CalculatePath(node);  
  6.         }  
  7.         //Create an ArrayList to store the neighboring nodes  
  8.         ArrayList neighbours = new ArrayList();  
  9.         GridManager.instance.GetNeighbours(node, neighbours);  
  10.         for (int i = 0; i < neighbours.Count; i++) {  
  11.             Node neighbourNode = (Node)neighbours[i];  
  12.             if (!closedList.Contains(neighbourNode)) {  
  13.                 float cost = HeuristicEstimateCost(node,  
  14.                         neighbourNode);  
  15.                 float totalCost = node.nodeTotalCost + cost;  
  16.                 float neighbourNodeEstCost = HeuristicEstimateCost(  
  17.                         neighbourNode, goal);  
  18.                 neighbourNode.nodeTotalCost = totalCost;  
  19.                 neighbourNode.parent = node;  
  20.                 neighbourNode.estimatedCost = totalCost +   
  21.                         neighbourNodeEstCost;  
  22.                 if (!openList.Contains(neighbourNode)) {  
  23.                     openList.Push(neighbourNode);  
  24.                 }  
  25.             }  
  26.         }  
  27.         //Push the current node to the closed list  
  28.         closedList.Push(node);  
  29.         //and remove it from openList  
  30.         openList.Remove(node);  
  31.     }  
  32.     if (node.position != goal.position) {  
  33.         Debug.LogError("Goal Not Found");  
  34.         return null;  
  35.     }  
  36.     return CalculatePath(node);  
  37. }  
這代碼實現類似於我們之前討論過的算法,所以如果你對特定的東西不清楚的話可以返回去看看.

  1. 獲得openList的第一個節點.記住每當新節點加入時openList都需要再次排序.所以第一個節點總是有到目的節點最低估計代價值.
  2. 檢查當前節點是否是目的節點,如果是推出while循環創建path數組.
  3. 創建數組列表保存當前正被處理的節點的臨近節點.使用GetNeighbours方法來從格子中檢索鄰接節點.
  4. 對於每一個在鄰接節點數組中的節點,我們檢查它是否已在closedList中.如果不在,計算代價值並使用新的代價值更新節點的屬性值,更新節點的父節點並將其放入openList中.
  5. 將當前節點壓入closedList中並將其從openList中移除.返回第一步.
如果在openList中沒有更多的節點,我們的當前節點應該是目標節點如果路徑存在的話.之後我們將當前節點作爲參數傳入CalculatePath方法中.

  1. private static ArrayList CalculatePath(Node node) {  
  2.     ArrayList list = new ArrayList();  
  3.     while (node != null) {  
  4.         list.Add(node);  
  5.         node = node.parent;  
  6.     }  
  7.     list.Reverse();  
  8.     return list;  
  9. }  
CalculatePath方法跟蹤每個節點的父節點對象並創建數組列表.他返回一個從目的節點到開始節點的ArrayList.由於我們需要從開始節點到目標節點的路徑,我們簡單調用一下Reverse方法就ok.

這就是我們的AStar類.我們將在下面的代碼裏寫一個測試腳本來檢驗所有的這些東西.之後創建一個場景並在其中使用它們.

TestCode Class

代碼如TestCode.cs所示,該類使用AStar類找到從開始節點到目的節點的路徑.

  1. using UnityEngine;  
  2. using System.Collections;  
  3. public class TestCode : MonoBehaviour {  
  4.     private Transform startPos, endPos;  
  5.     public Node startNode { getset; }  
  6.     public Node goalNode { getset; }  
  7.     public ArrayList pathArray;  
  8.     GameObject objStartCube, objEndCube;  
  9.     private float elapsedTime = 0.0f;  
  10.     //Interval time between pathfinding  
  11.     public float intervalTime = 1.0f;  
首先我們創建我們需要引用的變量.pathArray用於保存從AStar的FindPath方法返回的節點數組.

  1. void Start () {  
  2.     objStartCube = GameObject.FindGameObjectWithTag("Start");  
  3.     objEndCube = GameObject.FindGameObjectWithTag("End");  
  4.     pathArray = new ArrayList();  
  5.     FindPath();  
  6. }  
  7. void Update () {  
  8.     elapsedTime += Time.deltaTime;  
  9.     if (elapsedTime >= intervalTime) {  
  10.         elapsedTime = 0.0f;  
  11.         FindPath();  
  12.     }  
  13. }  
在Start方法中我們尋找標籤(tags)爲Start和End的對象並初始化pathArray.如果開始和結束的節點位置變了我們將嘗試在每一個我們所設置的intervalTime屬性時間間隔裏找到我們的新路徑.之後我們調用FindPath方法.

  1. void FindPath() {  
  2.     startPos = objStartCube.transform;  
  3.     endPos = objEndCube.transform;  
  4.     startNode = new Node(GridManager.instance.GetGridCellCenter(  
  5.             GridManager.instance.GetGridIndex(startPos.position)));  
  6.     goalNode = new Node(GridManager.instance.GetGridCellCenter(  
  7.             GridManager.instance.GetGridIndex(endPos.position)));  
  8.     pathArray = AStar.FindPath(startNode, goalNode);  
  9. }  
因爲我們在AStar類中實現了尋路算法,尋路現在變得簡單多了.首先,我們獲得開始和結束的遊戲對象(game objects).之後,我們使用GridManager的輔助方法創建新的Node對象,使用GetGridIndex來計算它們在格子中對應的行列位置.一旦我們將開始節點和目標節點作爲參數調用了AStar.FindPath方法並將返回的數組保存在pathArray屬性中.接下我們實現OnDrawGizmos方法來繪製並形象化(draw and visualize)我們找到的路徑.

  1. void OnDrawGizmos() {  
  2.     if (pathArray == null)  
  3.         return;  
  4.     if (pathArray.Count > 0) {  
  5.         int index = 1;  
  6.         foreach (Node node in pathArray) {  
  7.             if (index < pathArray.Count) {  
  8.                 Node nextNode = (Node)pathArray[index];  
  9.                 Debug.DrawLine(node.position, nextNode.position,  
  10.                     Color.green);  
  11.                 index++;  
  12.             }  
  13.         }  
  14.     }  
  15. }  
我們檢查了我們的pathArray並使用Debug.DrawLine方法來繪製線條連接起pathArray中的節點.當運行並測試程序時我們就能看到一條綠線從開始節點連接到目標節點,連線形成了一條路徑.

Scene setup

我們將要創建一個類似於下面截圖所展示的場景:


Sample test scene

我們將有一個平行光,開始以及結束遊戲對象,一些障礙物,一個被用作地面的平面實體和兩個空的遊戲對象,空對象身上放置GridManager和TestAstar腳本.這是我們的場景層級圖.


Scene hierarchy

創建一些立方體實體並給他們加上標籤Obstacle,當運行我們的尋路算法時我們需要尋找帶有該標籤的對象.


Obstacle nodes

創建一個立方體實體並加上標籤Start


Start node

創建另一個立方體實體並加上標籤End


End node

現在創建一個空的遊戲對象並將GridManager腳本賦給它.將其名字也設置回GridManager因爲在我們的腳本中使用該名稱尋找GridManager對象.這裏我們可以設置格子的行數和列數和每個格子的大小.


GridManager script

Testing

我們點擊Play按鈕實打實的看下我們的A*算法.默認情況下,一旦你播放當前場景Unity3D將會切換到Game視圖.由於我們的尋路形象化(visualization)代碼是爲我編輯器視圖中的調試繪製而寫,你需要切換回Scene視圖或者勾選Gizmos來查看找到的路徑.


現在在場景中嘗試使用編輯器的移動工具移動開始和結束節點.(不是在Game視圖中,而是在Scene視圖中)


如果從開始節點到目的節點有合法路徑,你應該看到路徑會對應更新並且是動態實時的更新.如果沒有路徑,你會在控制窗口中得到一條錯誤信息.

總結

在本章中,我們學習瞭如何在Unity3D環境中實現A*尋路算法.我們實現了自己的A*尋路類以及我們自己的格子類,隊列類和節點類.我們學習了IComparable接口並重寫了CompareTo方法.我們使用調試繪製功能(debug draw functionalities)來呈現我們的網格和路徑信息.有了Unity3D的navmesh和navagent功能你可能不必自己實現尋路算法.不管怎麼樣,他幫助你理解實現背後的基礎算法.

在下一章中,我們將查看如何擴展藏在A*背後的思想看看導航網格(navigation meshes).使用導航網格,在崎嶇的地形上尋路將變得容易得多.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章