/// <summary> /// Internal function that implements the path-finding algorithm. /// </summary> /// <param name="pGrid">Grid to search.</param> /// <param name="startPos">Starting position.</param> /// <param name="targetPos">Ending position.</param> /// <param name="distance">The type of distance, Euclidean or Manhattan.</param> /// <param name="ignorePrices">If true, will ignore tile price (how much it "cost" to walk on).</param> /// <returns>List of grid nodes that represent the path to walk.</returns> private static List <Node> _ImpFindPath(PGrid pGrid, PPoint startPos, PPoint targetPos, DistanceType distance = DistanceType.Euclidean, bool ignorePrices = false) { Node startNode = pGrid.nodes[startPos.x, startPos.y]; Node targetNode = pGrid.nodes[targetPos.x, targetPos.y]; List <Node> openSet = new List <Node>(); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node 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); if (currentNode == targetNode) { return(RetracePath(pGrid, startNode, targetNode)); } foreach (Node neighbour in pGrid.GetNeighbours(currentNode, distance)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour) * (ignorePrices ? 1 : (int)(10.0f * neighbour.price)); if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } } } } return(null); }
/// <summary> /// Find a path between two points. /// </summary> /// <param name="pGrid">Grid to search.</param> /// <param name="startPos">Starting position.</param> /// <param name="targetPos">Ending position.</param> /// <param name="distance">The type of distance, Euclidean or Manhattan.</param> /// <param name="ignorePrices">If true, will ignore tile price (how much it "cost" to walk on).</param> /// <returns>List of points that represent the path to walk.</returns> public static List <PPoint> FindPath(PGrid pGrid, PPoint startPos, PPoint targetPos, DistanceType distance = DistanceType.Euclidean, bool ignorePrices = false) { // find path List <Node> nodes_path = _ImpFindPath(pGrid, startPos, targetPos, distance, ignorePrices); // convert to a list of points and return List <PPoint> ret = new List <PPoint>(); if (nodes_path != null) { foreach (Node node in nodes_path) { ret.Add(new PPoint(node.gridX, node.gridY)); } } return(ret); }