Example #1
0
    public List <Node> findPath(Transform zombie)
    {
        Transform starter = nodefind.NearestPlayerNode(zombie);
        Transform ender   = nodefind.NearestPlayerNode(player);

        Node startNode  = starter.gameObject.GetComponent <Node> ();
        Node targetNode = ender.gameObject.GetComponent <Node> ();


        List <Node>    openSet   = new List <Node> ();
        HashSet <Node> closedSet = new HashSet <Node> ();
        List <Node>    route     = new List <Node> ();

        openSet.Add(startNode);


        while (openSet.Count > 0)
        {
            Node checker = openSet [0];
            for (int i = 1; i < openSet.Count; i++)
            {
                if (openSet[i].fCost < checker.fCost || openSet[i].fCost == checker.fCost)
                {
                    if (openSet[i].hCost < checker.hCost)
                    {
                        checker = openSet[i];
                    }
                }
            }

            openSet.Remove(checker);
            closedSet.Add(checker);

            if (checker == targetNode)
            {
                route = RetracePath(startNode, targetNode);
                break;
            }

            foreach (Node neighbour in checker.neighbours)
            {
                if (closedSet.Contains(neighbour))
                {
                    continue;
                }

                int newCostToNeighbour = checker.gCost + GetDistance(checker, neighbour);
                if (newCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour))
                {
                    neighbour.gCost  = newCostToNeighbour;
                    neighbour.hCost  = GetDistance(neighbour, targetNode);
                    neighbour.parent = checker;

                    if (!openSet.Contains(neighbour))
                    {
                        openSet.Add(neighbour);
                    }
                }
            }
        }
        route.Add(targetNode);


        return(route);
    }