- Unity 2018 Artificial Intelligence Cookbook(Second Edition)
- Jorge Palacios
- 147字
- 2021-07-16 18:11:36
How to do it...
Even though this recipe is only defining a function, please take into consideration the comments in the code for better understanding of the implementation and code flow:
- Declare the GetPathDFS function:
public List<Vertex> GetPathDFS(GameObject srcObj, GameObject dstObj) { // next steps }
- Establish whether input objects are null:
if (srcObj == null || dstObj == null) return new List<Vertex>();
- Declare and initialize the variables we need for the algorithm:
Vertex src = GetNearestVertex(srcObj.transform.position); Vertex dst = GetNearestVertex(dstObj.transform.position); Vertex[] neighbours; Vertex v; int[] previous = new int[vertices.Count]; for (int i = 0; i < previous.Length; i++) previous[i] = -1; previous[src.id] = src.id; Stack<Vertex> s = new Stack<Vertex>(); s.Push(src);
- Implement the DFS algorithm for finding a path:
while (s.Count != 0) { v = s.Pop(); if (ReferenceEquals(v, dst)) { return BuildPath(src.id, v.id, ref previous); } neighbours = GetNeighbours(v); foreach (Vertex n in neighbours) { if (previous[n.id] != -1) continue; previous[n.id] = v.id; s.Push(n); } }