예제 #1
0
            ////  define basic operators for this class

            #region IComparable (so nodes are sortable)

            public int CompareTo(object obj)
            {
                AStarNodeDep other     = (AStarNodeDep)obj;
                float        thisRank  = this.heuristicCost + this.totalCost;
                float        otherRank = other.heuristicCost + other.totalCost;

                return(thisRank.CompareTo(otherRank));
            }
예제 #2
0
        public static List <AStarNodeDep> FindPath(this AStarNodeDep[,] matrix, AStarNodeDep start, AStarNodeDep destination)
        {
            List <AStarNodeDep> edges = new List <AStarNodeDep>();
            List <AStarNodeDep> path  = new List <AStarNodeDep>();

            //  are start and destination the same?
            if (start.Equals(destination))
            {
                path.Add(start);
                return(path);
            }

            //  update heuristic costs for all nodes in the matrix
            foreach (AStarNodeDep node in matrix)
            {
                node.destination = destination.coordinate;
            }

            //  build the path
            edges.Add(start);
            bool pathFound = false;

            do
            {
                //  sort the edges by heuristic
                edges.Sort();

                //  select the first edge
                AStarNodeDep selectedEdge   = edges[0];
                Vector2      edgeCoordinate = selectedEdge.coordinate.ToVector2();

                //  get all neighbors of the edge
                List <AStarNodeDep> neighbors = new List <AStarNodeDep>();
                neighbors = matrix.GetNeighborsOf((int)edgeCoordinate.x, (int)edgeCoordinate.y, 1);

                //  set the neighbors' parents to the edge
                foreach (AStarNodeDep node in neighbors)
                {
                    node.parent = selectedEdge;
                }

                //  append all neighbors to the edge list
                edges.AddUniques(neighbors);

                //  move the edge to the searched list
                edges.Remove(selectedEdge);

                pathFound = selectedEdge.Equals(destination);
            } while (edges.Count > 0 && !pathFound);

            if (pathFound)
            {
                AStarNodeDep node = destination;
                do
                {
                    path.Add(node);
                    node = node.parent;
                } while (node != null);
                return(path);
            }
            else
            {
                return(null);
            }
        }
예제 #3
0
            ////  A* operations

            public bool CoordinateEquals(AStarNodeDep node)
            {
                return(this.CoordinateEquals(node.coordinate));
            }