Ejemplo n.º 1
0
    public void GeneratePathTo(int x, int y)
    {
        if (mapScript.UnitCanEnterTile(x, y) == false)
        {
            return;
        }

        Dictionary <Node, float> dist = new Dictionary <Node, float>();
        Dictionary <Node, Node>  prev = new Dictionary <Node, Node>();

        List <Node> unvisited = new List <Node>();

        Node source = mapScript.graph[posX, posY];
        Node target = mapScript.graph[x, y];

        dist[source] = 0;
        prev[source] = null;

        foreach (Node v in mapScript.graph)
        {
            if (v != source)
            {
                dist[v] = Mathf.Infinity;
                prev[v] = null;
            }
            unvisited.Add(v);
        }

        while (unvisited.Count > 0)
        {
            Node u = null;

            foreach (Node possibleU in unvisited)
            {
                if (u == null || dist[possibleU] < dist[u])
                {
                    u = possibleU;
                }
            }

            if (u == target)
            {
                break;
            }

            unvisited.Remove(u);

            foreach (Node v in u.neighbours)
            {
                float alt = dist[u] + mapScript.graph[u.x, u.y].movementCost;
                if (alt < dist[v])
                {
                    dist[v] = alt;
                    prev[v] = u;
                }
            }
        }

        if (prev[target] == null)
        {
            return;
        }

        List <Node> currentPath = new List <Node>();

        Node curr = target;

        while (curr != null)
        {
            currentPath.Add(curr);
            curr = prev[curr];
        }

        currentPath.Reverse();
        playerPath = currentPath;
    }