예제 #1
0
    private int[] Astar(GridElement startPos, GridElement endPos)
    {
        List <GridElement> openedList = new List <GridElement> {
            startPos
        };
        List <GridElement> closedList = new List <GridElement>();
        var grid = startPos.grid.GridElements;

        foreach (var z in grid)
        {
            foreach (var x in z)
            {
                GridElement pathNode = isGridElement(x);
                pathNode.gCost = int.MaxValue;
                pathNode.CalculateFCost();
                pathNode.cameFromNode = null;
            }
        }
        startPos.gCost = 0;
        startPos.hCost = ManhattanDistance(startPos, endPos);
        startPos.CalculateFCost();

        while (openedList.Count > 0)
        {
            GridElement currentGridElement = GetLowestFCost(openedList);
            if (currentGridElement == endPos)
            {
                return(CalcPath(endPos));
            }
            openedList.Remove(currentGridElement);
            closedList.Add(currentGridElement);

            foreach (var Node in getNeighbours(currentGridElement))
            {
                if (closedList.Contains(Node))
                {
                    continue;
                }
                int hujCost = 0;
                if (Node.unit)
                {
                    hujCost = Node.unit.GetComponent <UnitBase>().unitCounters["hp"] / 3;
                }
                int tempGCost = currentGridElement.gCost + ManhattanDistance(currentGridElement, Node) + hujCost;
                if (tempGCost < Node.gCost)
                {
                    Node.cameFromNode = currentGridElement;
                    Node.gCost        = tempGCost;
                    Node.hCost        = ManhattanDistance(Node, endPos);
                    Node.CalculateFCost();
                    if (!openedList.Contains(Node))
                    {
                        openedList.Add(Node);
                    }
                }
            }
        }
        int [] move = { 0, 0 };
        return(move);
    }