//================================================================
//
Copyright (C) Team Saluka
All Rights Reserved
//
Author: Goblin Balous
//
//================================================================
Using System.Collections;
Using System.Collections.Generic;
Using Unityengine;
Namespace Saruka
{
<summary>
A * algorithm
</summary>
public class AStar
{
Private AStar () {}
<summary>
A * search algorithm
</summary>
<param name= "Navgrid" > Navigation grids </param>
<param name= "StartPosition" > Start coordinates </param>
<param name= "targetposition" > Target point coordinates </param>
<param name= "heuristics" > Inspiring factor </param>
<returns> Paths </returns>
public static list<navnode> SearchPath (Navgrid navgrid, Vector3 startposition, Vector3 targetposition, heuristics Heuristics)
{
if (Navgrid = = null)
{
Debug.logerror ("You're using a A * algorithm, but not providing a navigation grid!") ");
return null;
}
Navnode startnode = navgrid.navnodefromworldposition (startposition);
Navnode TargetNode = navgrid.navnodefromworldposition (targetposition);
if (!targetnode.iswalkable) return null;
list<navnode> queuenodes = new list<navnode> ();
hashset<navnode> evaluatednodes = new hashset<navnode> ();
Queuenodes.add (Startnode);
while (Queuenodes.count > 0)
{
Navnode CurrentNode = queuenodes[0];
for (int i = 1; i < Queuenodes.count; i++)
if (Queuenodes[i].fcost < Currentnode.fcost | | queuenodes[i].fcost = = currentnode.fcost && queuenodes[i]. Hcost < Currentnode.hcost)
CurrentNode = Queuenodes[i];
Queuenodes.remove (CurrentNode);
Evaluatednodes.add (CurrentNode);
Find path, return path
if (CurrentNode = = TargetNode)
{
list<navnode> path = new list<navnode> ();
Navnode node = TargetNode;
while (node! = startnode)
{
Path. ADD (node);
node = node.parent;
}
Path. Reverse ();
return path;
}
foreach (Navnode neighbornode in Navgrid.getneighbornodes (CurrentNode))
{
if (!neighbornode.iswalkable | | evaluatednodes.contains (NEIGHBORNODE)) continue;
Float Newgcosttoneighbornode = currentnode.gcost + heuristics. Getheuristics (CurrentNode, Neighbornode);
if (!queuenodes.contains (neighbornode) | | Newgcosttoneighbornode < neighbornode.gcost)
{
if (!queuenodes.contains (Neighbornode)) Queuenodes.add (Neighbornode);
Neighbornode.gcost = Newgcosttoneighbornode;
Neighbornode.hcost = heuristics. Getheuristics (Neighbornode, TargetNode);
Neighbornode.parent = CurrentNode;
}
}
}
Path not found, return null
return null;
}
}
}
The elf's Perfect game room--ai, A * algorithm, realization