游戏AI实现-寻路算法(Dijkstra)

戴克斯特拉算法(英语:Dijkstra's algorithm),又称迪杰斯特拉算法、Dijkstra算法,是由荷兰计算机科学家艾兹赫尔·戴克斯特拉在1956年发现的算法。

算法过程:

1.首先设置开始节点的成本值为0,并将开始节点放入检测列表中。

2.将检测列表中的所有点按到目标点所需的成本值排序,选择成本最小的节点作为当前节点,并将其移出检测列表。

3.将当前点周围的点中不包含在检测列表中的点加入到检测列表,将周围点加入到已检测列表中。

4.更新检测列表中的节点到当前节点的成本值。

5.重复2,3,4直到找到目标点。

代码实现:

cs 复制代码
public class Dijkstra : FindPathAlgorithm
{
    public Dijkstra(int[,] mapData, int xCount, int zCount) : base(mapData, xCount, zCount){}

    public override List<Vector2Int> FindPath(Vector2Int startPos, Vector2Int goalPos)
    {
        DataNode dataNode = this.DijkstraFind(startPos, goalPos);
        if (dataNode == null)
        {
            Debug.LogError("寻路有误,请检查参数是否正确");
            return null;
        }
        return Utils.GetPath(dataNode);
    }

    DataNode DijkstraFind(Vector2Int startPos, Vector2Int goalPos)
    {
        //存储要检测的点
        List<DataNode> frontier = new List<DataNode>();
        //存储已经检测的点
        List<Vector2Int> reached = new List<Vector2Int>();

        DataNode startNode = new DataNode(startPos, null);
        startNode.gCost = 0;
        frontier.Add(startNode);
        reached.Add(startPos);

        while (frontier.Count > 0)
        {
            DataNode currentNode = GetLowestgCostNode(frontier);
            frontier.Remove(currentNode);
            if (currentNode.pos == goalPos)
            {
                Debug.Log("完成!!!");
                return new DataNode(goalPos, currentNode.parent);
            }

            List<DataNode> neighbors = GetNeighbors(currentNode.pos, reached);
            foreach (DataNode neighbourNode in neighbors)
            {
                if (!frontier.Contains(neighbourNode))
                {
                    neighbourNode.parent = currentNode;
                    frontier.Add(neighbourNode);
                }
                reached.Add(neighbourNode.pos);
            }

            this.UpdateCost(frontier, currentNode);
        }

        return null;
    }

    //更新成本值
    void UpdateCost(List<DataNode> nodes, DataNode currentNode)
    {
        for (int i = 0; i < nodes.Count; i++)
        {
            int newCost = currentNode.gCost + CalculateDistanceCost(nodes[i].pos, currentNode.pos);
            if (nodes[i].gCost > newCost)
            {
                nodes[i].gCost = newCost;
            }
        }
    }

    List<DataNode> GetNeighbors(Vector2Int current, List<Vector2Int> reached)
    {
        List<DataNode> neighbors = new List<DataNode>();
        for (int i = 0; i < Utils.pointDir.Count; i++)
        {
            Vector2Int neighbor = current + Utils.pointDir[i];
            if (this.IsCanAdd(neighbor, reached))
            {
                neighbors.Add(new DataNode(neighbor, null));
            }
        }
        return neighbors;
    }

    bool IsCanAdd(Vector2Int current, List<Vector2Int> reached)
    {
        if (reached.Contains(current))
            return false;
        if (current.x >= 0 && current.y >= 0 && current.x < MapData.m_MapData.GetLength(1) && current.y < MapData.m_MapData.GetLength(0))
        {
            //如果是障碍物,则不能被Add
            if (MapData.m_MapData[current.y, current.x] == 1)
            {
                return false;
            }
            return true;
        }
        return false;
    }

    private int CalculateDistanceCost(Vector2Int a, Vector2Int b)
    {
        return Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
    }

    private DataNode GetLowestgCostNode(List<DataNode> pathNodeList)
    {
        DataNode lowestFCostNode = pathNodeList[0];
        for (int i = 1; i < pathNodeList.Count; i++)
        {
            if (pathNodeList[i].gCost < lowestFCostNode.gCost)
            {
                lowestFCostNode = pathNodeList[i];
            }
        }
        return lowestFCostNode;
    }
}

结果:

参考链接:

Pathfinding in Unity - Part3: Dijkstra Algorithm Theory (youtube.com)

Pathfinding in Unity - Part4: Dijkstra Algorithm Implementation (youtube.com)

How Dijkstra's Algorithm Works (youtube.com)

戴克斯特拉算法 - 维基百科,自由的百科全书 (wikipedia.org)

相关推荐
井队Tell2 小时前
打造高清3D虚拟世界|零基础学习Unity HDRP高清渲染管线(第九天)
学习·3d·unity
千年奇葩12 小时前
Unity性能优化之:利用CUDA加速Unity实现大规模并行计算。从环境搭建到实战案例
c++·人工智能·unity·游戏引擎·cuda
AA陈超12 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-25 属性信息数据资产
c++·游戏·ue5·游戏引擎·虚幻
17岁的勇气15 小时前
Unity Shader unity文档学习笔记(二十二):雪地几种实现方式(1. 2D贴花式 2.3D曲面细分并且实现顶点偏移)
笔记·学习·unity·shader
科技快报1 天前
引入实时 3D 渲染技术,地平线与 Unity 开启车载交互空间化时代
3d·unity·交互
爱吃小胖橘1 天前
高效对象池设计:提升Unity性能的关键
开发语言·unity·c#·游戏引擎
沉默的记录者1 天前
unity 2021反向遮罩的毛边
unity·游戏引擎
沧海归城1 天前
Unity_Canvas_Canvas Scaler画布缩放器。
unity·游戏引擎
一只一只2 天前
Unity 3D笔记(进阶部分)——《B站阿发你好》
笔记·3d·unity·游戏引擎
yi碗汤园2 天前
【一文了解】八大排序-冒泡排序、选择排序
开发语言·前端·算法·unity·c#·1024程序员节