コード例 #1
0
ファイル: FindPath.cs プロジェクト: tuita520/AstarForUnity
    /// <summary>
    /// A*算法,寻找最短路径
    /// </summary>
    /// <param name="start"></param>
    /// <param name="end"></param>
    private void FindingPath(Vector3 start, Vector3 end)
    {
        Node startNode = m_Grid.GetFromPosition(start);
        Node endNode   = m_Grid.GetFromPosition(end);

        openList.Clear();
        closeSet.Clear();
        openList.Add(startNode);
        int count = openList.Count;

        while (count > 0)
        {
            // 寻找开启列表中的F最小的节点,如果F相同,选取H最小的
            Node currentNode = openList[0];
            for (int i = 0; i < count; i++)
            {
                Node node = openList[i];
                if (node.FCost < currentNode.FCost || node.FCost == currentNode.FCost && node.m_hCost < currentNode.m_hCost)
                {
                    currentNode = node;
                }
            }
            // 把当前节点从开启列表中移除,并加入到关闭列表中
            openList.Remove(currentNode);
            closeSet.Add(currentNode);
            // 如果是目的节点,返回
            if (currentNode == endNode)
            {
                GeneratePath(startNode, endNode);
                return;
            }
            // 搜索当前节点的所有相邻节点
            foreach (var node in m_Grid.GetNeighor(currentNode))
            {
                // 如果节点不可通过或者已在关闭列表中,跳出
                if (!node.m_CanWalk || closeSet.Contains(node))
                {
                    continue;
                }
                int gCost = currentNode.m_gCost + GetDistanceNodes(currentNode, node);
                // 如果新路径到相邻点的距离更短 或者不在开启列表中
                if (gCost < node.m_gCost || !openList.Contains(node))
                {
                    // 更新相邻点的F,G,H
                    node.m_gCost = gCost;
                    node.m_hCost = GetDistanceNodes(node, endNode);
                    // 设置相邻点的父节点为当前节点
                    node.m_Parent = currentNode;
                    // 如果不在开启列表中,加入到开启列表中
                    if (!openList.Contains(node))
                    {
                        openList.Add(node);
                    }
                }
            }
        }
    }