我有一个包含三种路径寻找算法的类:Depthwise,Breadthwise和AStart。我在GameObject脚本中使用这些方法,该脚本必须在图形中巡逻,但是当我运行它时,对象不会移动,它会保留在第一个节点中。
public static List<Node> Depthwise(Node start, Node end) {
Stack<Node> work = new Stack<Node>();
List<Node> visited = new List<Node>();
work.Push(start);
visited.Add(start);
start.history = new List<Node>();
while(work.Count > 0)
{
Node current = work.Pop();
if(current == end)
{
List<Node> result = current.history;
result.Add(current);
return result;
}
else
{
for (int i = 0; i < current.neighbors.Length; i++)
{
Node currentChild = current.neighbors[i];
if (!visited.Contains(currentChild))
{
work.Push(currentChild);
visited.Add(currentChild);
currentChild.history = new List<Node>(current.history);
currentChild.history.Add(current);
}
}
}
}
return null;
}
public static List<Node> Breadthwise(Node start, Node end) {
Queue<Node> work = new Queue<Node>();
List<Node> visited = new List<Node>();
work.Enqueue(start);
visited.Add(start);
start.history = new List<Node>();
while(work.Count > 0)
{
Node current = work.Dequeue();
if(current == end)
{
List<Node> result = current.history;
result.Add(current);
return result;
//we found a solution
}else
{
for(int i=0; i < current.neighbors.Length; i++)
{
Node currentChild = current.neighbors[i];
if (!visited.Contains(currentChild))
{
work.Enqueue(currentChild);
visited.Add(currentChild);
currentChild.history = new List<Node>(current.history);
currentChild.history.Add(current);
}
}
}
}
///No available path
return null;
}
public static List<Node> AStar(Node start, Node end)
{
List<Node> visited = new List<Node>();
List<Node> work = new List<Node>();
start.history = new List<Node>();
start.g = 0;
start.h = Vector3.Distance(start.transform.position, end.transform.position);
visited.Add(start);
work.Add(start);
while (work.Count > 0)
{
//get the current one
Node current = work[0];
for (int i = 0; i < work.Count; i++)
{
//check if answer is here
if (work[i] == end)
{
//return path
List<Node> result = work[i].history;
result.Add(work[i]);
return result;
}
if (work[i].F < current.F)
{
current = work[i];
}
}
work.Remove(current);
//traverse children
for(int i=0; i<current.neighbors.Length; i++)
{
Node currentChild = current.neighbors[i];
if (!visited.Contains(currentChild))
{
visited.Add(currentChild);
currentChild.history = new List<Node>(current.history);
currentChild.history.Add(current);
//g-certain
currentChild.g = current.g + Vector3.Distance(current.transform.position, currentChild.transform.position);
//h-heuristic
currentChild.h = Vector3.Distance(currentChild.transform.position, end.transform.position);
work.Add(currentChild);
}
}
}
return null;
}