Unity A*寻路算法

Unity中自带有NavMeshAgent寻路组件,很好用很方便,功能也挺多的,不过性能可能比不上A寻路算法,但是A算法也有一个缺点,就是寻的路线不一定是最短的,但却是较短的,可以满足寻路的需求。

简易地图

在这里插入图片描述
如图所示简易地图, 其中绿色方块的是起点 (用 A 表示), 中间蓝色的是障碍物, 红色的方块 (用B 表示) 是目的地. 为了可以用一个二维数组来表示地图, 我们将地图划分成一个个的小方块.

二维数组在游戏中的应用是很多的, 比如贪吃蛇和俄罗斯方块基本原理就是移动方块而已. 而大型游戏的地图, 则是将各种"地貌"铺在这样的小方块上.

寻路步骤

1. 从起点 A 开始, 把它作为待处理的方格存入一个"开启列表", 开启列表就是一个等待检查方格的列表.

2. 寻找起点 A 周围可以到达的方格, 将它们放入"开启列表", 并设置它们的"父方格"为 A.

3. 从"开启列表"中删除起点 A, 并将起点 A 加入"关闭列表", "关闭列表"中存放的都是不需要再次检查的方格

在这里插入图片描述
图中浅绿色描边的方块表示已经加入 “开启列表” 等待检查. 淡蓝色描边的起点 A 表示已经放入"关闭列表" , 它不需要再执行检查.

从 “开启列表” 中找出相对最靠谱的方块, 什么是最靠谱? 它们通过公式 F=G+H 来计算.

F = G + H
G 表示从起点 A 移动到网格上指定方格的移动耗费 (可沿斜方向移动).
H 表示从指定的方格移动到终点 B 的预计耗费 (H 有很多计算方法, 这里我们设定只可以上下左右移动).

在这里插入图片描述

我们假设横向移动一个格子的耗费为 10, 为了便于计算, 沿斜方向移动一个格子耗费是 14. 为了更直观的展示如何运算 FGH, 图中方块的左上角数字表示 F, 左下角表示 G, 右下角表示 H. 看看是否跟你心里想的结果一样?

从 “开启列表” 中选择 F 值最低的方格 C (绿色起始方块 A 右边的方块), 然后对它进行如下处理:

4. 把它从 “开启列表” 中删除, 并放到 “关闭列表” 中.

5. 检查它所有相邻并且可以到达 (障碍物和 “关闭列表” 的方格都不考虑) 的方格. 如果这些方格还不在 “开启列表” 里的话, 将它们加入 “开启列表”, 计算这些方格的 G, H 和 F 值各是多少, 并设置它们的 “父方格” 为 C.

6. 如果某个相邻方格 D 已经在 “开启列表” 里了, 检查如果用新的路径 (就是经过 C 的路径) 到达它的话, G 值是否会更低一些, 如果新的 G 值更低, 那就把它的 “父方格” 改为目前选中的方格 C, 然后重新计算它的 F 值和 G 值 (H 值不需要重新计算, 因为对于每个方块, H 值是不变的). 如果新的 G值比较高, 就说明经过 C 再到达 D 不是一个明智的选择, 因为它需要更远的路, 这时我们什么也不做.

在这里插入图片描述
如图, 我们选中了 C 因为它的 F 值最小, 我们把它从 “开启列表” 中删除, 并把它加入 “关闭列表”. 它右边上下三个都是墙, 所以不考虑它们. 它左边是起始方块, 已经加入到 “关闭列表” 了, 也不考虑. 所以它周围的候选方块就只剩下 4 个. 让我们来看看 C 下面的那个格子, 它目前的 G 是 14, 如果通过 C 到达它的话, G 将会是 10 + 10, 这比 14 要大, 因此我们什么也不做.

然后我们继续从 “开启列表” 中找出 F 值最小的, 但我们发现 C 上面的和下面的同时为 54, 这时怎么办呢? 这时随便取哪一个都行, 比如我们选择了 C 下面的那个方块 D.

在这里插入图片描述

D 右边已经右上方的都是墙, 所以不考虑, 但为什么右下角的没有被加进 “开启列表” 呢? 因为如果 C 下面的那块也不可以走, 想要到达 C 右下角的方块就需要从 “方块的角” 走了, 在程序中设置是否允许这样走. (图中的示例不允许这样走)

在这里插入图片描述

就这样, 我们从 “开启列表” 找出 F 值最小的, 将它从 “开启列表” 中移掉, 添加到 “关闭列表”.

再继续找出它周围可以到达的方块, 如此循环下去…
那么什么时候停止呢? —— 当我们发现 “开始列表” 里出现了目标终点方块的时候, 说明路径已经被找到.

如何找回所寻的路径呢?
除了起始方块, 每一个曾经或者现在还在 “开启列表” 里的方块, 它都有一个 “父方
块”, 通过 “父方块” 可以索引到最初的 “起始方块”, 这就是路径.

代码部分

先创建一个Point的类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Point
{
    public Point Parent { get; set; }
    public float F { get; set; }
    public float G { get; set; }
    public float H { get; set; }

    public int X { get; set; }
    public int Y { get; set; }

    public bool IsWall { get; set; }

    public Point(int x,int y,Point parent=null)
    {
        X = x;
        Y = y;
        Parent = parent;
        IsWall = false;
    }

    /// <summary>
    /// 更新父节点的g值
    /// </summary>
    public void UpdateParent(Point parent,float g)
    {
        Parent = parent;
        G = g;
        F = G + H;
    }
}

再创建一个AStart算法的主要实现类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AStar : MonoBehaviour
{
    private int mapWidth = 8;
    private int mapHeight = 6;
    private Point[,] map;
    void Start()
    {
        InitMap();
        Point start = map[2, 3];
        Point end = map[6, 3];
        FindPath(start, end);
        ShowPath(start, end);
    }

    /// <summary>
    /// 初始化地图
    /// </summary>
    private void InitMap()
    {
        map = new Point[mapWidth, mapHeight];
        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                map[x, y] = new Point(x, y);
            }
        }
        map[4, 2].IsWall = true;
        map[4, 3].IsWall = true;
        map[4, 4].IsWall = true;
    }

    /// <summary>
    /// 创建Cube当做地图
    /// </summary>
    private void CreateCube(int x,int y,Color color)
    {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        go.transform.position = new Vector3(x, y, 0);
        go.GetComponent<Renderer>().material.color = color;
    }

    /// <summary>
    /// 显示路径坐标
    /// </summary>
    private void ShowPath(Point start, Point end)
    {
        Point temp = end;
        while (true)
        {
            //Debug.Log(temp.X + "-" + temp.Y);
            Color color = Color.gray;
            if(temp==start)
            {
                color = Color.green;
            }
            if(temp==end)
            {
                color = Color.red;
            }
            CreateCube(temp.X, temp.Y, color);
            if (temp.Parent == null)
                break;
            temp = temp.Parent;
        }
        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                if(map[x,y].IsWall)
                {
                    CreateCube(x, y, Color.blue);
                }
            }
        }
    }

    /// <summary>
    /// 查找路径
    /// </summary>
    /// <param name="start">开始点</param>
    /// <param name="end">目标点</param>
    private void FindPath(Point start,Point end)
    {
        List<Point> openList = new List<Point>();
        List<Point> closeList = new List<Point>();
        openList.Add(start);
        while(openList.Count>0)
        {
            Point point = FindMinFOfPoint(openList);
            openList.Remove(point);
            closeList.Add(point);
            List<Point> surroundPointsList = GetSurroundPoints(point);
            PointsFilter(surroundPointsList, closeList);
            foreach (Point surroundPoint in surroundPointsList)
            {
                if(openList.IndexOf(surroundPoint)>-1)
                {
                    float nowG = CalculateG(surroundPoint, point);
                    if(nowG<surroundPoint.G)
                    {
                        surroundPoint.UpdateParent(point, nowG);
                    }
                }
                else
                {
                    surroundPoint.Parent = point;
                    CalculateF(surroundPoint, end);
                    openList.Add(surroundPoint);
                }
            }
            //判断一下是否到达了目标点
            if(openList.IndexOf(end)>-1)
            {
                break;
            }
        }
    }

    /// <summary>
    /// 过滤掉关闭列表中的Point
    /// </summary>
    private void PointsFilter(List<Point> src,List<Point> closePoint)
    {
        foreach (Point p in closePoint)
        {
            if(src.IndexOf(p)>-1)
            {
                src.Remove(p);
            }
        }
    }

    private List<Point> GetSurroundPoints(Point point)
    {
        Point up = null, down = null, left = null, right = null;
        Point lu = null, ld = null, ru = null, rd = null;
        //取得上下左右的Point
        if(point.Y<mapHeight-1)
        {
            up = map[point.X, point.Y + 1];
        }
        if(point.Y>0)
        {
            down = map[point.X, point.Y - 1];
        }
        if(point.X>0)
        {
            left = map[point.X - 1, point.Y];
        }
        if(point.X<mapWidth-1)
        {
            right = map[point.X + 1, point.Y];
        }
        //取得左上、左下、右上、右下的Point
        if (left != null&& up != null)
        {
            lu = map[point.X - 1, point.Y + 1];
        }
        if(left!=null&&down!=null)
        {
            ld = map[point.X - 1, point.Y - 1];
        }
        if (right != null && up != null)
        {
            ru = map[point.X + 1, point.Y + 1];
        }
        if (right != null && down != null)
        {
            rd = map[point.X + 1, point.Y - 1];
        }
        
        List<Point> pointList = new List<Point>();
        //周围的Point如果不是墙就可以走
        if(up!=null&&up.IsWall==false)
        {
            pointList.Add(up);
        }
        if (down != null && down.IsWall == false)
        {
            pointList.Add(down);
        }
        if (left != null && left.IsWall == false)
        {
            pointList.Add(left);
        }
        if (right != null && right.IsWall == false)
        {
            pointList.Add(right);
        }
        //两边也不是墙才可以走
        if(lu!=null&&lu.IsWall==false&&left.IsWall==false&&up.IsWall==false)
        {
            pointList.Add(lu);
        }
        if (ld != null && ld.IsWall == false && left.IsWall == false && down.IsWall == false)
        {
            pointList.Add(ld);
        }
        if (ru != null && ru.IsWall == false && right.IsWall == false && up.IsWall == false)
        {
            pointList.Add(ru);
        }
        if (rd != null && rd.IsWall == false && right.IsWall == false && down.IsWall == false)
        {
            pointList.Add(rd);
        }
        return pointList;
    }

    /// <summary>
    /// 查找开启列表中的最小F值
    /// </summary>
    /// <param name="openList"></param>
    /// <returns></returns>
    private Point FindMinFOfPoint(List<Point> openList)
    {
        float f = float.MaxValue;
        Point temp = null;
        foreach (Point p in openList)
        {
            if(p.F<f)
            {
                temp = p;
                f = p.F;
            }
        }
        return temp;
    }

    /// <summary>
    /// 计算F的值
    /// </summary>
    /// <param name="now">当前位置</param>
    /// <param name="end">目标位置</param>
    private void CalculateF(Point now,Point end)
    {
        //F = G + H
        float h = Mathf.Abs(end.X - now.X) + Mathf.Abs(end.Y - now.Y);
        float g = 0;
        if(now.Parent==null)
        {
            g = 0;
        }
        else
        {
            g = Vector2.Distance(new Vector2(now.X, now.Y), new Vector2(now.Parent.X, now.Parent.Y)) + now.Parent.G;
        }
        float f = g + h;
        now.F = f;
        now.G = g;
        now.H = h;
    }

    /// <summary>
    /// 计算F的值
    /// </summary>
    private float CalculateG(Point now,Point parent)
    {
        return Vector2.Distance(new Vector2(now.X, now.Y), new Vector2(parent.X, parent.Y)) + parent.G;
    }
}

将AStart脚本挂载在空物体上,运行之后的效果:
在这里插入图片描述
蓝色块是障碍物,绿色块是起点,红色块是终点,灰色块是所寻得的路径。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值