/// <summary> /// Finds the shortest path from the start to the end position. /// </summary> /// <param name="beginPosition">The (x, y) pair that represents the start location.</param> /// <param name="endPosition">The (x, y) pair that represents the end location.</param> /// <returns>A list of mapNodes representing the shortest path from start to end.</returns> public static List <MapNode> getShortestPathTo(Vector2 beginPosition, Vector2 endPosition) { MapNode start = getNearestNodeTo(beginPosition.X, beginPosition.Y, entryPoint), goal = getNearestNodeTo(endPosition.X, endPosition.Y, entryPoint); List <AStarElement> pQueue = new List <AStarElement>(); //priority queue pQueue.Add(new AStarElement(start, goal)); AStarElement toAdd = null; while (!pQueue[0].isFullPath()) { //The shortest path found so far will always be at the head of the list, //so per aStar, build on that path. AStarElement best = pQueue[0]; foreach (MapNode n in best.getLastNode().getAllNodes()) { if (best.exists(n)) { continue; } toAdd = new AStarElement(best); toAdd.addNode(n); pQueue.Add(toAdd); if (n == goal) { break; } } if (!best.isFullPath()) { pQueue.Remove(best); } pQueue.Sort(); //Custom sorting that makes shortest path be sorted to head of list. } //while return(pQueue[0].getNodes()); }
/// <summary> /// Creates a new path using an existing AStar path. /// </summary> /// <param name="obj">The AStarElement from which to build this element.</param> public AStarElement(AStarElement obj) { chain = new List <MapNode>(); foreach (MapNode n in obj.chain) { chain.Add(n); } target = obj.target; }
public int CompareTo(object obj) { AStarElement o = (AStarElement)obj; if (f == o.f) { return(h() - o.h()); } return(f - o.f); }