1. 程式人生 > >Unity3d利用A*尋路演算法實現尋路模擬

Unity3d利用A*尋路演算法實現尋路模擬

這裡我先引用一篇詳細文章來介紹A*演算法

文章內容如下

簡易地圖

 

如圖所示簡易地圖, 其中綠色方塊的是起點 ( A 表示), 中間藍色的是障礙物, 紅色的方塊 ( B 表示) 是目的地. 為了可以用一個二維陣列來表示地圖, 我們將地圖劃分成一個個的小方塊.

二維陣列在遊戲中的應用是很多的, 比如貪吃蛇和俄羅斯方塊基本原理就是移動方塊而已. 而大型

 遊戲的地圖, 則是將各種"地貌"鋪在這樣的小方塊上.

尋路步驟

1. 從起點開始把它作為待處理的方格存入一個"開啟列表", 開啟列表就是一個等待檢查方格

 的列表.

2. 尋找起點周圍可以到達的方格將它們放入"開啟列表", 並設定它們的"父方格"

A.

3. 從"開啟列表"中刪除起點 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 值各是多少並設定它們的 "父方格"  C.

6. 如果某個相鄰方格 D 已經在 "開啟列表" 裡了, 檢查如果用新的路徑 (就是經過 C 的路徑) 到達它的話, G 值是否會更低一些

如果新的值更低那就把它的 "父方格" 改為目前選中的方格 C, 然後重新計算它的值和 (H 值不需要重新計算因為對於每個方塊, H 值是不變的). 如果新的值比較高就說明經過再到達不是一個明智的選擇因為它需要更遠的路這時我們什麼也不做.

 

如圖, 我們選中了 C 因為它的 F 值最小, 我們把它從 "開啟列表" 中刪除, 並把它加入 "關閉列表". 它右邊上下三個都是牆, 所以不考慮它們. 它左邊是起始方塊, 已經加入到 "關閉列表" , 也不考慮. 所以它周圍的候選方塊就只剩下 4 . 讓我們來看看 C 下面的那個格子, 它目前的 G  14, 

果通過 C 到達它的話, G 將會是 10 + 10, 這比 14 要大, 因此我們什麼也不做.

然後我們繼續從 "開啟列表" 中找出 F 值最小的, 但我們發現 C 上面的和下面的同時為 54, 

時怎麼辦呢? 這時隨便取哪一個都行, 比如我們選擇了 C 下面的那個方塊 D.


右邊已經右上方的都是牆, 所以不考慮, 但為什麼右下角的沒有被加進 "開啟列表" ?

因為如果 C 下面的那塊也不可以走, 想要到達 C 右下角的方塊就需要從 "方塊的角" 走了, 在程式中設定是否允許這樣走. (圖中的示例不允許這樣走)


就這樣, 我們從 "開啟列表" 找出 F 值最小的, 將它從 "開啟列表" 中移掉, 新增到 "關閉列表".

再繼續找出它周圍可以到達的方塊, 如此迴圈下去...

那麼什麼時候停止呢?—— 當我們發現 "開始列表" 裡出現了目標終點方塊的時候, 說明路徑已經

被找到.

如何找回路徑


如上圖所示, 除了起始方塊, 每一個曾經或者現在還在 "開啟列表" 裡的方塊, 它都有一個 "父方塊", 通過 "父方塊" 可以索引到最初的 "起始方塊", 這就是路徑.

Unity程式碼實現

演算法類

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

public class AStarAlgorithm 
{
    private const int mGridWidth = 20;    
    private const int mGridHeight = 10;

    //使用二維陣列儲存點網格    
    public AStarPoint[,] mPointGrid = new AStarPoint[mGridWidth,mGridHeight];
    //儲存路徑方格子
    public List<AStarPoint> mPathPosList = new List<AStarPoint>();

    private static AStarAlgorithm _instance;
    public static AStarAlgorithm GetInsatnce
    {
        get
        {
            if (_instance == null)
            {
                _instance = new AStarAlgorithm();
            }

            return _instance;
        }
    }

    public AStarAlgorithm()
    {
        InitPoint();
    }

    //在網格上設定點的資訊
    private void InitPoint()
    {
        for (int i = 0; i < mGridWidth; i++)
        {
            for (int j = 0; j < mGridHeight; j++)
            {                
                mPointGrid[i, j] = new AStarPoint(i, j);
            }
        }

        //設定障礙物
        mPointGrid[4, 2].mIsObstacle = true;
        mPointGrid[4, 3].mIsObstacle = true;
        mPointGrid[4, 4].mIsObstacle = true;
        mPointGrid[4, 5].mIsObstacle = true;
        mPointGrid[4, 6].mIsObstacle = true;

        //顯示障礙物
        for (int x = 0; x < mGridWidth; x++)
        {
            for (int y = 0; y < mGridHeight; y++)
            {
                if (mPointGrid[x, y].mIsObstacle)
                {
                    CreatePath(x, y, Color.blue);
                }
            }
        }
    }

    public void ClearGrid()
    {
        for (int x = 0; x < mGridWidth; x++)
        {
            for (int y = 0; y < mGridHeight; y++)
            {
                if (!mPointGrid[x, y].mIsObstacle)
                {
                    if (mPointGrid[x, y].mGameObject != null)
                    {
                        GameObject.Destroy(mPointGrid[x, y].mGameObject);
                        mPointGrid[x, y].mGameObject = null;

                        //重新設定父節點
                        mPointGrid[x, y].mParentPoint = null;
                    }
                }
            }
        }
    }

    //尋路
    public List<AStarPoint> FindPath(AStarPoint mStartPoint, AStarPoint mEndPoint)
    {
        if (mEndPoint.mIsObstacle || mStartPoint.mPosition == mEndPoint.mPosition)
        {
            return  null;
        }

        //開啟列表
        List<AStarPoint> openPointList = new List<AStarPoint>();
        //關閉列表
        List<AStarPoint> closePointList = new List<AStarPoint>();

        openPointList.Add(mStartPoint);

        while (openPointList.Count > 0)
        {
            //尋找開啟列表中最小預算值的表格
            AStarPoint minFPoint = FindPointWithMinF(openPointList);
            //將當前表格從開啟列表移除 在關閉列表新增
            openPointList.Remove(minFPoint);
            closePointList.Add(minFPoint);
            //找到當前點周圍的全部點
            List<AStarPoint> surroundPoints = FindSurroundPoint(minFPoint);            
            //在周圍的點中,將關閉列表裡的點移除掉
            SurroundPointsFilter(surroundPoints, closePointList);
            //尋路邏輯
            foreach (var surroundPoint in surroundPoints)
            {
                if (openPointList.Contains(surroundPoint))
                {
                    //計算下新路徑下的G值(H值不變的,比較G相當於比較F值)
                    float newPathG = CalcG(surroundPoint, minFPoint);
                    if (newPathG < surroundPoint.mG)
                    {
                        surroundPoint.mG = newPathG;
                        surroundPoint.mF = surroundPoint.mG + surroundPoint.mH;
                        surroundPoint.mParentPoint = minFPoint;
                    }
                }
                else
                {
                    //將點之間的
                    surroundPoint.mParentPoint = minFPoint;
                    CalcF(surroundPoint, mEndPoint);
                    openPointList.Add(surroundPoint);
                }
            }

            //如果開始列表中包含了終點,說明找到路徑
            if (openPointList.IndexOf(mEndPoint) > -1)
            {
                break;
            }
        }

        return ShowPath(mStartPoint, mEndPoint);
    }

    private List<AStarPoint> ShowPath(AStarPoint start, AStarPoint end)
    {
        mPathPosList.Clear();

        AStarPoint temp = end;
        while (true)
        {
            mPathPosList.Add(temp);

            Color c = Color.white;
            if (temp == start)
            {
                c = Color.green;
            }
            else if (temp == end)
            {
                c = Color.red;
            }
            CreatePath(temp.mPositionX, temp.mPositionY, c);

            if (temp.mParentPoint == null)
                break;
            temp = temp.mParentPoint;
        }

        return mPathPosList;
    }

    private void CreatePath(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;
        go.transform.SetParent(GameObject.Find("Path").transform);

        if (mPointGrid[x, y].mGameObject != null)
        {
            GameObject.Destroy(mPointGrid[x, y].mGameObject);             
        }
        mPointGrid[x, y].mGameObject = go;
    }

    //尋找預計值最小的格子
    private AStarPoint FindPointWithMinF(List<AStarPoint> openPointList)
    {
        float f = float.MaxValue;
        AStarPoint temp = null;
        foreach (AStarPoint p in openPointList)
        {
            if (p.mF < f)
            {
                temp = p;
                f = p.mF;
            }
        }
        return temp;
    }

    //尋找周圍的全部點
    private List<AStarPoint> FindSurroundPoint(AStarPoint point)
    {
        List<AStarPoint> list = new List<AStarPoint>();

        ////////////判斷周圍的八個點是否在網格內/////////////
        AStarPoint up = null, down = null, left = null, right = null;
        AStarPoint lu = null, ru = null, ld = null, rd = null;
        if (point.mPositionY < mGridHeight - 1)
        {
            up = mPointGrid[point.mPositionX, point.mPositionY + 1];
        }
        if (point.mPositionY > 0)
        {
            down = mPointGrid[point.mPositionX, point.mPositionY - 1];
        }
        if (point.mPositionX > 0)
        {
            left = mPointGrid[point.mPositionX - 1, point.mPositionY];
        }
        if (point.mPositionX < mGridWidth - 1)
        {
            right = mPointGrid[point.mPositionX + 1, point.mPositionY];
        }
        if (up != null && left != null)
        {
            lu = mPointGrid[point.mPositionX - 1, point.mPositionY + 1];
        }
        if (up != null && right != null)
        {
            ru = mPointGrid[point.mPositionX + 1, point.mPositionY + 1];
        }
        if (down != null && left != null)
        {
            ld = mPointGrid[point.mPositionX - 1, point.mPositionY - 1];
        }
        if (down != null && right != null)
        {
            rd = mPointGrid[point.mPositionX + 1, point.mPositionY - 1];
        }
        

        /////////////將可以經過的表格新增到開啟列表中/////////////
        if (down != null && down.mIsObstacle == false)
        {
            list.Add(down);
        }
        if (up != null && up.mIsObstacle == false)
        {
            list.Add(up);
        }
        if (left != null && left.mIsObstacle == false)
        {
            list.Add(left);
        }
        if (right != null && right.mIsObstacle == false)
        {
            list.Add(right);
        }
        if (lu != null && lu.mIsObstacle == false && left.mIsObstacle == false && up.mIsObstacle == false)
        {
            list.Add(lu);
        }
        if (ld != null && ld.mIsObstacle == false && left.mIsObstacle == false && down.mIsObstacle == false)
        {
            list.Add(ld);
        }
        if (ru != null && ru.mIsObstacle == false && right.mIsObstacle == false && up.mIsObstacle == false)
        {
            list.Add(ru);
        }
        if (rd != null && rd.mIsObstacle == false && right.mIsObstacle == false && down.mIsObstacle == false)
        {
            list.Add(rd);
        }

        return list;
    }

    //將關閉帶你從周圍點列表中關閉
    private void SurroundPointsFilter(List<AStarPoint> surroundPoints, List<AStarPoint> closePoints)
    {
        foreach (var closePoint in closePoints)
        {
            if (surroundPoints.Contains(closePoint))
            {
                Debug.Log("將關閉列表的點移除");
                surroundPoints.Remove(closePoint);
            }
        }
    }

    //計算最小預算值點G值
    private float CalcG(AStarPoint surround, AStarPoint minFPoint)
    {
        return Vector3.Distance(surround.mPosition, minFPoint.mPosition) + minFPoint.mG;
    }

    //計算該點到終點的F值
    private void CalcF(AStarPoint now, AStarPoint end)
    {
        //F = G + H
        float h = Mathf.Abs(end.mPositionX - now.mPositionX) + Mathf.Abs(end.mPositionY - now.mPositionY);
        float g = 0;
        if (now.mParentPoint == null)
        {
            g = 0;
        }
        else
        {
            g = Vector2.Distance(new Vector2(now.mPositionX, now.mPositionY), new Vector2(now.mParentPoint.mPositionX, now.mParentPoint.mPositionY)) + now.mParentPoint.mG;
        }
        float f = g + h;
        now.mF = f;
        now.mG = g;
        now.mH = h;
    }
}


其中AStarPoint是儲存點的資訊(位置、父格子、實體物件)

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


/// <summary>
/// 儲存尋路點資訊
/// </summary>
public class AStarPoint
{
    //父“格子”
    public AStarPoint mParentPoint { get; set; }
    //格子顯示物件
    public GameObject mGameObject { get; set; }

    public float mF { get; set; }
    public float mG { get; set; }
    public float mH { get; set; }
    //點的位置
    public Vector2 mPosition { get; set; }
    public int mPositionX { get; set; }
    public int mPositionY { get; set; }
    //該點是否處於障礙物
    public bool mIsObstacle { get; set; }

    public AStarPoint(int positionX,int positionY)
    {
        this.mPositionX = positionX;
        this.mPositionY = positionY;
        this.mPosition = new Vector2(mPositionX, mPositionY);
        this.mParentPoint = null;
    }
}

尋路模擬

建立一個DoPlayer測試類,用於模仿一個物體的尋路
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoPlayer : MonoBehaviour
{
    private GameObject mCubeParent;

    //儲存路徑點
    private List<AStarPoint> mPathPosList;

    //網格大小
    private const int mGridWidth = 20;
    private const int mGridHeight = 10;

    private AStarPoint[,] mPointGrid;

    private AStarPoint mStartPos;
    private AStarPoint mEndPos { get; set; }

    //每一秒發生位移
    private float mTime = 0.7f;
    private float mTimer = 0.0f;

    //目標點
    private int mTargetX { get; set; }
    private int mTargetY { get; set; }

    private void Start()
    {
        mCubeParent = GameObject.Find("Plane");

        mPointGrid = AStarAlgorithm.GetInsatnce.mPointGrid;
        mStartPos = mPointGrid[0, 0];

        InitBG();
    }

    private void Update()
    {
        mTimer += Time.deltaTime;
        if (mTimer >= mTime)
        {
            mTimer = 0;
            Walk();
        }
    }

    private void Walk()
    {     
        if (mPathPosList != null && mPathPosList.Count > 1)
        {
            mStartPos = mPathPosList[mPathPosList.Count - 1];
            Color color = mStartPos.mGameObject.GetComponent<Renderer>().material.color;
            mPathPosList.Remove(mStartPos);
            Destroy(mStartPos.mGameObject);
            mStartPos.mGameObject = null;
            
            mStartPos = mPathPosList[mPathPosList.Count - 1];
            mStartPos.mGameObject.GetComponent<Renderer>().material.color = color;
            
        }
    }

    private void InitBG()
    {
        for (int i = 0; i < mGridWidth; i++)
        {
            for (int j = 0; j < mGridHeight; j++)
            {
                CreateCube(i, j, Color.gray);
            }
        }
    }


    private void CreateCube(int x, int y, Color color)
    {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        go.transform.SetParent(mCubeParent.transform);
        go.transform.position = new Vector3(x, y, 0);
        go.transform.localScale = new Vector3(0.9f, 0.9f, 0.9f);
        go.GetComponent<Renderer>().material.color = color;

        go.AddComponent<Cube>().FindPath = FindPath;
    }

    public void FindPath(int mTargetX, int mTargetY)
    {
        if (mPathPosList != null)
        {
            mPathPosList.Clear();
        }
        AStarAlgorithm.GetInsatnce.ClearGrid();

        //網格點物件重新重新整理了  需要使用網格來索引到點 mPathPosList儲存的點是之前的AStarPoint
        this.mEndPos = mPointGrid[mTargetX, mTargetY];
        this.mStartPos = mPointGrid[mStartPos.mPositionX, mStartPos.mPositionY];

        mPathPosList = AStarAlgorithm.GetInsatnce.FindPath(this.mStartPos, mEndPos);
    }
}

其中建立的Cube網格類程式碼如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cube : MonoBehaviour
{
    public delegate void VoidDelegate(int x, int y);
    public VoidDelegate FindPath;

    private void OnMouseDown()
    {
        if (FindPath != null)
        {
            FindPath((int)this.transform.position.x, (int)this.transform.position.y);
        }
    }
}

效果展示

效果顯示正常,綠色方塊代表主角位置,紅色方塊代表目標點,白色方塊代表路徑