Question by
andreyazbyn · Nov 16, 2015 at 01:34 PM ·
c#pathfindingrangeastar
A* all nodes within range
I made a script that finds a path from node A to node B. How can i make a method that returns a array of the nodes within a certain range?
Here's what i got so far:
void FindPath(Vector2 startPos, Vector2 targetPos)
{
Tile startNode = map.tiles[(int)startPos.x, -(int)startPos.y];
Tile targetNode = map.tiles[(int)targetPos.x,- (int)targetPos.y];
List<Tile> openSet = new List<Tile>();
HashSet<Tile> closedSet = new HashSet<Tile>();
openSet.Add(startNode);
while (openSet.Count > 0) {
Tile currentNode = openSet[0];
for (int i = 1; i < openSet.Count; i ++) {
if (openSet[i].fCost < currentNode.fCost || openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost) {
currentNode = openSet[i];
}
}
openSet.Remove(currentNode);
closedSet.Add(currentNode);
while (openSet.Count > 0)
{
Tile currentNode = openSet.RemoveFirst();
closedSet.Add(currentNode);
if (currentNode == targetNode)
{
RetracePath(startNode, targetNode);
return;
}
foreach (Tile neighbour in currentNode.neighbours)
{
if (!neighbour.walkable || closedSet.Contains(neighbour))
{
continue;
}
int newMovementCostToNeigbour = currentNode.gCost + GetDistance(currentNode, neighbour)+neighbour.movementPenalty;
if (newMovementCostToNeigbour < neighbour.gCost ||!openSet.Contains(neighbour))
{
neighbour.gCost = newMovementCostToNeigbour;
neighbour.hCost = GetDistance(neighbour, targetNode);
neighbour.parent = currentNode;
if (!openSet.Contains(neighbour))
{
openSet.Add(neighbour);
}
else openSet.UpdateItem(neighbour);
}
}
}
}
void RetracePath(Tile startNode, Tile endNode){
List<Tile> path = new List<Tile>();
Tile currentNode = endNode;
while (currentNode != startNode) {
path.Add(currentNode);
currentNode= currentNode.parent;
}
path.Reverse();
map.path = path;
}
int GetDistance(Tile nodeA, Tile nodeB)
{
int distX = Mathf.Abs(nodeA.xPos - nodeB.xPos);
int distY = Mathf.Abs(nodeA.yPos - nodeB.yPos);
if (distX > distY)
{
return 2 * distX + distY;
}
return distX + 2 *distY;
}
Comment