Unity 寻路A*算法

原文地址:blog.liujunliang.com.cn

这里我先引用一篇详细文章来介绍A*算法

本文源码链接:点击打开链接

文章内容如下

简易地图

 

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

二维数组在游戏中的应用是很多的, 比如贪吃蛇和俄罗斯方块基本原理就是移动方块而已. 而大型

 游戏的地图, 则是将各种"地貌"铺在这样的小方块上.

寻路步骤

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

 的列表.

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

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

 

图中浅绿色描边的方块表示已经加入 "开启列表" 等待检查. 淡蓝色描边的起点 A 表示已经放入

 "关闭列表" , 它不需要再执行检查.

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

F = G + H 

表示从起点 A 移动到网格上指定方格的移动耗费 (可沿斜方向移动).

 表示从指定的方格移动到终点 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.


右边已经右上方的都是墙, 所以不考虑, 但为什么右下角的没有被加进 "开启列表" ? 

因为如果 下面的那块也不可以走想要到达 C 右下角的方块就需要从 "方块的角走了在程序中设置是否允许这样走. (图中的示例不允许这样走)


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

再继续找出它周围可以到达的方块, 如此循环下去...

那么什么时候停止呢? —— 当我们发现 "开始列表" 里出现了目标终点方块的时候, 说明路径已经

被找到.

如何找回路径


如上图所示, 除了起始方块, 每一个曾经或者现在还在 "开启列表" 里的方块, 它都有一个 "父方块", 通过 "父方块" 可以索引到最初的 "起始方块", 这就是路径.

Unity代码实现

算法类

[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class AStarAlgorithm   
  6. {  
  7.     private const int mGridWidth = 20;      
  8.     private const int mGridHeight = 10;  
  9.   
  10.     //使用二维数组存储点网格      
  11.     public AStarPoint[,] mPointGrid = new AStarPoint[mGridWidth,mGridHeight];  
  12.     //存储路径方格子  
  13.     public List<AStarPoint> mPathPosList = new List<AStarPoint>();  
  14.   
  15.     private static AStarAlgorithm _instance;  
  16.     public static AStarAlgorithm GetInsatnce  
  17.     {  
  18.         get  
  19.         {  
  20.             if (_instance == null)  
  21.             {  
  22.                 _instance = new AStarAlgorithm();  
  23.             }  
  24.   
  25.             return _instance;  
  26.         }  
  27.     }  
  28.   
  29.     public AStarAlgorithm()  
  30.     {  
  31.         InitPoint();  
  32.     }  
  33.   
  34.     //在网格上设置点的信息  
  35.     private void InitPoint()  
  36.     {  
  37.         for (int i = 0; i < mGridWidth; i++)  
  38.         {  
  39.             for (int j = 0; j < mGridHeight; j++)  
  40.             {                  
  41.                 mPointGrid[i, j] = new AStarPoint(i, j);  
  42.             }  
  43.         }  
  44.   
  45.         //设置障碍物  
  46.         mPointGrid[4, 2].mIsObstacle = true;  
  47.         mPointGrid[4, 3].mIsObstacle = true;  
  48.         mPointGrid[4, 4].mIsObstacle = true;  
  49.         mPointGrid[4, 5].mIsObstacle = true;  
  50.         mPointGrid[4, 6].mIsObstacle = true;  
  51.   
  52.         //显示障碍物  
  53.         for (int x = 0; x < mGridWidth; x++)  
  54.         {  
  55.             for (int y = 0; y < mGridHeight; y++)  
  56.             {  
  57.                 if (mPointGrid[x, y].mIsObstacle)  
  58.                 {  
  59.                     CreatePath(x, y, Color.blue);  
  60.                 }  
  61.             }  
  62.         }  
  63.     }  
  64.   
  65.     public void ClearGrid()  
  66.     {  
  67.         for (int x = 0; x < mGridWidth; x++)  
  68.         {  
  69.             for (int y = 0; y < mGridHeight; y++)  
  70.             {  
  71.                 if (!mPointGrid[x, y].mIsObstacle)  
  72.                 {  
  73.                     if (mPointGrid[x, y].mGameObject != null)  
  74.                     {  
  75.                         GameObject.Destroy(mPointGrid[x, y].mGameObject);  
  76.                         mPointGrid[x, y].mGameObject = null;  
  77.   
  78.                         //重新设置父节点  
  79.                         mPointGrid[x, y].mParentPoint = null;  
  80.                     }  
  81.                 }  
  82.             }  
  83.         }  
  84.     }  
  85.   
  86.     //寻路  
  87.     public List<AStarPoint> FindPath(AStarPoint mStartPoint, AStarPoint mEndPoint)  
  88.     {  
  89.         if (mEndPoint.mIsObstacle || mStartPoint.mPosition == mEndPoint.mPosition)  
  90.         {  
  91.             return  null;  
  92.         }  
  93.   
  94.         //开启列表  
  95.         List<AStarPoint> openPointList = new List<AStarPoint>();  
  96.         //关闭列表  
  97.         List<AStarPoint> closePointList = new List<AStarPoint>();  
  98.   
  99.         openPointList.Add(mStartPoint);  
  100.   
  101.         while (openPointList.Count > 0)  
  102.         {  
  103.             //寻找开启列表中最小预算值的表格  
  104.             AStarPoint minFPoint = FindPointWithMinF(openPointList);  
  105.             //将当前表格从开启列表移除 在关闭列表添加  
  106.             openPointList.Remove(minFPoint);  
  107.             closePointList.Add(minFPoint);  
  108.             //找到当前点周围的全部点  
  109.             List<AStarPoint> surroundPoints = FindSurroundPoint(minFPoint);              
  110.             //在周围的点中,将关闭列表里的点移除掉  
  111.             SurroundPointsFilter(surroundPoints, closePointList);  
  112.             //寻路逻辑  
  113.             foreach (var surroundPoint in surroundPoints)  
  114.             {  
  115.                 if (openPointList.Contains(surroundPoint))  
  116.                 {  
  117.                     //计算下新路径下的G值(H值不变的,比较G相当于比较F值)  
  118.                     float newPathG = CalcG(surroundPoint, minFPoint);  
  119.                     if (newPathG < surroundPoint.mG)  
  120.                     {  
  121.                         surroundPoint.mG = newPathG;  
  122.                         surroundPoint.mF = surroundPoint.mG + surroundPoint.mH;  
  123.                         surroundPoint.mParentPoint = minFPoint;  
  124.                     }  
  125.                 }  
  126.                 else  
  127.                 {  
  128.                     //将点之间的  
  129.                     surroundPoint.mParentPoint = minFPoint;  
  130.                     CalcF(surroundPoint, mEndPoint);  
  131.                     openPointList.Add(surroundPoint);  
  132.                 }  
  133.             }  
  134.   
  135.             //如果开始列表中包含了终点,说明找到路径  
  136.             if (openPointList.IndexOf(mEndPoint) > -1)  
  137.             {  
  138.                 break;  
  139.             }  
  140.         }  
  141.   
  142.         return ShowPath(mStartPoint, mEndPoint);  
  143.     }  
  144.   
  145.     private List<AStarPoint> ShowPath(AStarPoint start, AStarPoint end)  
  146.     {  
  147.         mPathPosList.Clear();  
  148.   
  149.         AStarPoint temp = end;  
  150.         while (true)  
  151.         {  
  152.             mPathPosList.Add(temp);  
  153.   
  154.             Color c = Color.white;  
  155.             if (temp == start)  
  156.             {  
  157.                 c = Color.green;  
  158.             }  
  159.             else if (temp == end)  
  160.             {  
  161.                 c = Color.red;  
  162.             }  
  163.             CreatePath(temp.mPositionX, temp.mPositionY, c);  
  164.   
  165.             if (temp.mParentPoint == null)  
  166.                 break;  
  167.             temp = temp.mParentPoint;  
  168.         }  
  169.   
  170.         return mPathPosList;  
  171.     }  
  172.   
  173.     private void CreatePath(int x, int y, Color color)  
  174.     {  
  175.         GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);  
  176.         go.transform.position = new Vector3(x, y, 0);  
  177.         go.GetComponent<Renderer>().material.color = color;  
  178.         go.transform.SetParent(GameObject.Find("Path").transform);  
  179.   
  180.         if (mPointGrid[x, y].mGameObject != null)  
  181.         {  
  182.             GameObject.Destroy(mPointGrid[x, y].mGameObject);               
  183.         }  
  184.         mPointGrid[x, y].mGameObject = go;  
  185.     }  
  186.   
  187.     //寻找预计值最小的格子  
  188.     private AStarPoint FindPointWithMinF(List<AStarPoint> openPointList)  
  189.     {  
  190.         float f = float.MaxValue;  
  191.         AStarPoint temp = null;  
  192.         foreach (AStarPoint p in openPointList)  
  193.         {  
  194.             if (p.mF < f)  
  195.             {  
  196.                 temp = p;  
  197.                 f = p.mF;  
  198.             }  
  199.         }  
  200.         return temp;  
  201.     }  
  202.   
  203.     //寻找周围的全部点  
  204.     private List<AStarPoint> FindSurroundPoint(AStarPoint point)  
  205.     {  
  206.         List<AStarPoint> list = new List<AStarPoint>();  
  207.   
  208.         判断周围的八个点是否在网格内/  
  209.         AStarPoint up = null, down = null, left = null, right = null;  
  210.         AStarPoint lu = null, ru = null, ld = null, rd = null;  
  211.         if (point.mPositionY < mGridHeight - 1)  
  212.         {  
  213.             up = mPointGrid[point.mPositionX, point.mPositionY + 1];  
  214.         }  
  215.         if (point.mPositionY > 0)  
  216.         {  
  217.             down = mPointGrid[point.mPositionX, point.mPositionY - 1];  
  218.         }  
  219.         if (point.mPositionX > 0)  
  220.         {  
  221.             left = mPointGrid[point.mPositionX - 1, point.mPositionY];  
  222.         }  
  223.         if (point.mPositionX < mGridWidth - 1)  
  224.         {  
  225.             right = mPointGrid[point.mPositionX + 1, point.mPositionY];  
  226.         }  
  227.         if (up != null && left != null)  
  228.         {  
  229.             lu = mPointGrid[point.mPositionX - 1, point.mPositionY + 1];  
  230.         }  
  231.         if (up != null && right != null)  
  232.         {  
  233.             ru = mPointGrid[point.mPositionX + 1, point.mPositionY + 1];  
  234.         }  
  235.         if (down != null && left != null)  
  236.         {  
  237.             ld = mPointGrid[point.mPositionX - 1, point.mPositionY - 1];  
  238.         }  
  239.         if (down != null && right != null)  
  240.         {  
  241.             rd = mPointGrid[point.mPositionX + 1, point.mPositionY - 1];  
  242.         }  
  243.           
  244.   
  245.         /将可以经过的表格添加到开启列表中/  
  246.         if (down != null && down.mIsObstacle == false)  
  247.         {  
  248.             list.Add(down);  
  249.         }  
  250.         if (up != null && up.mIsObstacle == false)  
  251.         {  
  252.             list.Add(up);  
  253.         }  
  254.         if (left != null && left.mIsObstacle == false)  
  255.         {  
  256.             list.Add(left);  
  257.         }  
  258.         if (right != null && right.mIsObstacle == false)  
  259.         {  
  260.             list.Add(right);  
  261.         }  
  262.         if (lu != null && lu.mIsObstacle == false && left.mIsObstacle == false && up.mIsObstacle == false)  
  263.         {  
  264.             list.Add(lu);  
  265.         }  
  266.         if (ld != null && ld.mIsObstacle == false && left.mIsObstacle == false && down.mIsObstacle == false)  
  267.         {  
  268.             list.Add(ld);  
  269.         }  
  270.         if (ru != null && ru.mIsObstacle == false && right.mIsObstacle == false && up.mIsObstacle == false)  
  271.         {  
  272.             list.Add(ru);  
  273.         }  
  274.         if (rd != null && rd.mIsObstacle == false && right.mIsObstacle == false && down.mIsObstacle == false)  
  275.         {  
  276.             list.Add(rd);  
  277.         }  
  278.   
  279.         return list;  
  280.     }  
  281.   
  282.     //将关闭带你从周围点列表中关闭  
  283.     private void SurroundPointsFilter(List<AStarPoint> surroundPoints, List<AStarPoint> closePoints)  
  284.     {  
  285.         foreach (var closePoint in closePoints)  
  286.         {  
  287.             if (surroundPoints.Contains(closePoint))  
  288.             {  
  289.                 Debug.Log("将关闭列表的点移除");  
  290.                 surroundPoints.Remove(closePoint);  
  291.             }  
  292.         }  
  293.     }  
  294.   
  295.     //计算最小预算值点G值  
  296.     private float CalcG(AStarPoint surround, AStarPoint minFPoint)  
  297.     {  
  298.         return Vector3.Distance(surround.mPosition, minFPoint.mPosition) + minFPoint.mG;  
  299.     }  
  300.   
  301.     //计算该点到终点的F值  
  302.     private void CalcF(AStarPoint now, AStarPoint end)  
  303.     {  
  304.         //F = G + H  
  305.         float h = Mathf.Abs(end.mPositionX - now.mPositionX) + Mathf.Abs(end.mPositionY - now.mPositionY);  
  306.         float g = 0;  
  307.         if (now.mParentPoint == null)  
  308.         {  
  309.             g = 0;  
  310.         }  
  311.         else  
  312.         {  
  313.             g = Vector2.Distance(new Vector2(now.mPositionX, now.mPositionY), new Vector2(now.mParentPoint.mPositionX, now.mParentPoint.mPositionY)) + now.mParentPoint.mG;  
  314.         }  
  315.         float f = g + h;  
  316.         now.mF = f;  
  317.         now.mG = g;  
  318.         now.mH = h;  
  319.     }  
  320. }  


其中AStarPoint是存储点的信息(位置、父格子、实体对象)

[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5.   
  6. /// <summary>  
  7. /// 存储寻路点信息  
  8. /// </summary>  
  9. public class AStarPoint  
  10. {  
  11.     //父“格子”  
  12.     public AStarPoint mParentPoint { getset; }  
  13.     //格子显示对象  
  14.     public GameObject mGameObject { getset; }  
  15.   
  16.     public float mF { getset; }  
  17.     public float mG { getset; }  
  18.     public float mH { getset; }  
  19.     //点的位置  
  20.     public Vector2 mPosition { getset; }  
  21.     public int mPositionX { getset; }  
  22.     public int mPositionY { getset; }  
  23.     //该点是否处于障碍物  
  24.     public bool mIsObstacle { getset; }  
  25.   
  26.     public AStarPoint(int positionX,int positionY)  
  27.     {  
  28.         this.mPositionX = positionX;  
  29.         this.mPositionY = positionY;  
  30.         this.mPosition = new Vector2(mPositionX, mPositionY);  
  31.         this.mParentPoint = null;  
  32.     }  
  33. }<span style="background-color:rgb(51,153,153);">  
  34. </span>  


寻路模拟

创建一个DoPlayer测试类,用于模仿一个物体的寻路
[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class DoPlayer : MonoBehaviour  
  6. {  
  7.     private GameObject mCubeParent;  
  8.   
  9.     //存储路径点  
  10.     private List<AStarPoint> mPathPosList;  
  11.   
  12.     //网格大小  
  13.     private const int mGridWidth = 20;  
  14.     private const int mGridHeight = 10;  
  15.   
  16.     private AStarPoint[,] mPointGrid;  
  17.   
  18.     private AStarPoint mStartPos;  
  19.     private AStarPoint mEndPos { getset; }  
  20.   
  21.     //每一秒发生位移  
  22.     private float mTime = 0.7f;  
  23.     private float mTimer = 0.0f;  
  24.   
  25.     //目标点  
  26.     private int mTargetX { getset; }  
  27.     private int mTargetY { getset; }  
  28.   
  29.     private void Start()  
  30.     {  
  31.         mCubeParent = GameObject.Find("Plane");  
  32.   
  33.         mPointGrid = AStarAlgorithm.GetInsatnce.mPointGrid;  
  34.         mStartPos = mPointGrid[0, 0];  
  35.   
  36.         InitBG();  
  37.     }  
  38.   
  39.     private void Update()  
  40.     {  
  41.         mTimer += Time.deltaTime;  
  42.         if (mTimer >= mTime)  
  43.         {  
  44.             mTimer = 0;  
  45.             Walk();  
  46.         }  
  47.     }  
  48.   
  49.     private void Walk()  
  50.     {       
  51.         if (mPathPosList != null && mPathPosList.Count > 1)  
  52.         {  
  53.             mStartPos = mPathPosList[mPathPosList.Count - 1];  
  54.             Color color = mStartPos.mGameObject.GetComponent<Renderer>().material.color;  
  55.             mPathPosList.Remove(mStartPos);  
  56.             Destroy(mStartPos.mGameObject);  
  57.             mStartPos.mGameObject = null;  
  58.               
  59.             mStartPos = mPathPosList[mPathPosList.Count - 1];  
  60.             mStartPos.mGameObject.GetComponent<Renderer>().material.color = color;  
  61.               
  62.         }  
  63.     }  
  64.   
  65.     private void InitBG()  
  66.     {  
  67.         for (int i = 0; i < mGridWidth; i++)  
  68.         {  
  69.             for (int j = 0; j < mGridHeight; j++)  
  70.             {  
  71.                 CreateCube(i, j, Color.gray);  
  72.             }  
  73.         }  
  74.     }  
  75.   
  76.   
  77.     private void CreateCube(int x, int y, Color color)  
  78.     {  
  79.         GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);  
  80.         go.transform.SetParent(mCubeParent.transform);  
  81.         go.transform.position = new Vector3(x, y, 0);  
  82.         go.transform.localScale = new Vector3(0.9f, 0.9f, 0.9f);  
  83.         go.GetComponent<Renderer>().material.color = color;  
  84.   
  85.         go.AddComponent<Cube>().FindPath = FindPath;  
  86.     }  
  87.   
  88.     public void FindPath(int mTargetX, int mTargetY)  
  89.     {  
  90.         if (mPathPosList != null)  
  91.         {  
  92.             mPathPosList.Clear();  
  93.         }  
  94.         AStarAlgorithm.GetInsatnce.ClearGrid();  
  95.   
  96.         //网格点对象重新刷新了  需要使用网格来索引到点 mPathPosList存储的点是之前的AStarPoint  
  97.         this.mEndPos = mPointGrid[mTargetX, mTargetY];  
  98.         this.mStartPos = mPointGrid[mStartPos.mPositionX, mStartPos.mPositionY];  
  99.   
  100.         mPathPosList = AStarAlgorithm.GetInsatnce.FindPath(this.mStartPos, mEndPos);  
  101.     }  
  102. }  

其中创建的Cube网格类代码如下
[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Cube : MonoBehaviour  
  6. {  
  7.     public delegate void VoidDelegate(int x, int y);  
  8.     public VoidDelegate FindPath;  
  9.   
  10.     private void OnMouseDown()  
  11.     {  
  12.         if (FindPath != null)  
  13.         {  
  14.             FindPath((int)this.transform.position.x, (int)this.transform.position.y);  
  15.         }  
  16.     }  
  17. }  

效果展示

效果显示正常,绿色方块代表主角位置,红色方块代表目标点,白色方块代表路径




原文地址:blog.liujunliang.com.cn

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值