Ejemplo n.º 1
0
    public List <PathNode> FindPath(int startX, int startY, int endX, int endY, int minX, int minY, int maxX, int maxY)
    {
        //如果不在grid内,也发回找不到路径
        if (endX < minX || endY < minY || endX >= maxX || endY >= maxY)
        {
            return(null);
        }

        PathNode startNode = GetNode(startX, startY);
        PathNode endNode   = GetNode(endX, endY);

        oppenList = new List <PathNode> {
            startNode
        };
        closeList = new List <PathNode> ();
        for (int x = minX; x < maxX; x++)
        {
            for (int y = minY; y < maxY; y++)
            {
                //每个点初始化
                PathNode pathNode = grid.GetTGridObject(x, y);
                pathNode.gcost = int.MaxValue;
                pathNode.CaculateFcost();
                pathNode.cameFromNode = null;
            }
        }
        //初始点初始化
        startNode.gcost = 0;
        startNode.hcost = CaculateDistanceCost(startNode, endNode);
        startNode.CaculateFcost();

        while (oppenList.Count > 0)
        {
            PathNode currentNode = GetLowerFcostNode(oppenList);
            if (!currentNode.GetIsThroughable())
            {
                //如果当前点是墙
                oppenList.Remove(currentNode);
                closeList.Add(currentNode);
                continue;
            }
            if (currentNode == endNode)
            {
                //到达终点
                return(CaculatePath(currentNode));
            }
            oppenList.Remove(currentNode);
            closeList.Add(currentNode);
            foreach (PathNode neighbourNode in GetNeighbourList(currentNode, minX, minY, maxX, maxY))
            {
                //如果neighbourNode已经算过了
                if (closeList.Contains(neighbourNode))
                {
                    continue;
                }
                //判断新Gcost是否比旧Gcost小
                int tentativeGcost = currentNode.gcost + CaculateDistanceCost(currentNode, neighbourNode);
                if (tentativeGcost < neighbourNode.gcost)
                {
                    neighbourNode.gcost        = tentativeGcost;
                    neighbourNode.cameFromNode = currentNode;
                    neighbourNode.hcost        = CaculateDistanceCost(neighbourNode, endNode);
                    neighbourNode.CaculateFcost();
                    if (!oppenList.Contains(neighbourNode))
                    {
                        oppenList.Add(neighbourNode);
                    }
                }
            }
        }
        //找不到路径了
        return(null);
    }