示例#1
0
    public List <Node> FindPath(Vector3 start, Vector3 end)
    {
        Node startN = grid.NodeFromWorldPoint(start);
        Node endN   = grid.NodeFromWorldPoint(end);

        List <Node>    open   = new List <Node>();
        HashSet <Node> closed = new HashSet <Node>();

        open.Add(startN);

        while (open.Count > 0)
        {
            Node curr = open[open.Count - 1];

            open.RemoveAt(open.Count - 1);
            closed.Add(curr);

            if (curr == endN)
            {
                return(MakePath(startN, endN));
            }

            List <Node> nearby = new List <Node>();
            foreach (Node n in grid.GetNearbyNodes(curr))
            {
                if (n.isSolid || closed.Contains(n))
                {
                    continue;
                }

                if (!open.Contains(n))
                {
                    n.parent = curr;
                    n.gCost  = curr.gCost + ManhattanDistance(n, curr);
                    n.hCost  = ManhattanDistance(n, curr);
                    nearby.Add(n);
                }
            }

            nearby.Sort((x, y) => y.fCost - x.fCost);
            open = MergeLists(open, nearby);
        }

        return(new List <Node>());
    }