1. 程式人生 > >(C#)A*演算法虛擬碼及原始碼

(C#)A*演算法虛擬碼及原始碼

using UnityEngine;
using System.Collections;

public class Node
{
    /*邏輯中用的*/
    public int gCost;
    public int hCost;
    public int fCost
    {
        get { return gCost + hCost; }
    }
    public Node parent;

    /*在Unity當中用的*/
    public bool canWalk;
    //網格的下標
    public int gridX;
    public int gridY;
    //節點的位置
    public Vector3 worldPos;

    public Node(bool _canWalk, Vector3 position, int x, int y)
    {
        canWalk = _canWalk;
        worldPos = position;
        gridX = x;
        gridY = y;
    }
}

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

public class Grid : MonoBehaviour
{
    //存放點節點的陣列
    public Node[,] grid;

    //網格的大小
    public Vector2 gridSize;
    //節點的大小
    public float nodeRadius;
    public float nodeDiameter;
    //一個層,代表可不可以通過
    public LayerMask cantLayer;

    //x和y方向上各有多少個格子
    public int gridContX;
    public int gridContY;

    //起點
    public Transform start;

    //用來儲存路徑的列表
    public List<Node> path = new List<Node>();


    void Start ()
    {
        cantLayer = LayerMask.GetMask("CantWalk");
        nodeDiameter = nodeRadius * 2;
        //gridContX = (int)(gridSize.x / nodeDiameter);
        gridContX = Mathf.RoundToInt(gridSize.x / nodeDiameter);
        gridContY = Mathf.RoundToInt(gridSize.y / nodeDiameter);

        grid = new Node[gridContX, gridContY];
        CreatGrid();
    }
	
	void Update ()
    {
	
	}
    //建立格子
    void CreatGrid()
    {
        //網格起點
        Vector3 startPoint = transform.position - gridSize.y / 2 * Vector3.forward - gridSize.x / 2 * Vector3.right;

        for (int i = 0; i < gridContX; i++)
        {
            for (int j = 0; j < gridContY; j++)
            {
                Vector3 worldPos = startPoint + Vector3.right * (nodeDiameter * i + nodeRadius) + Vector3.forward * (nodeDiameter * j + nodeRadius);
                //檢測有沒有碰到不能走的層上的物體
                bool canwalk = !Physics.CheckSphere(worldPos, nodeRadius, cantLayer);

                grid[i, j] = new Node(canwalk, worldPos, i, j);
            }
        }
    }

    //Unity中的輔助類
    void OnDrawGizmos()
    {
        if (grid == null)
        {
            return;
        }
        foreach (Node node in grid)
        {
            if (node.canWalk)
            {
                Gizmos.color = Color.yellow;
                Gizmos.DrawCube(node.worldPos, (nodeDiameter - 0.02f) * new Vector3(1, 0.2f, 1));
            }
            else
            {
                Gizmos.color = Color.red;
                Gizmos.DrawCube(node.worldPos, (nodeDiameter - 0.02f) * new Vector3(1, 0.2f, 1));
            }
        }

        //畫出起點的位置
        Node startNode = FindWithPosition(start.position);
        if (startNode.canWalk)
        {
            Gizmos.color = Color.black;
            Gizmos.DrawCube(startNode.worldPos, (nodeDiameter - 0.02f) * new Vector3(1, 0.2f, 1));
        }


        //畫路徑
        if(path != null)
        {
            foreach (var node in path)
            {
                Gizmos.color = Color.blue;
                Gizmos.DrawCube(node.worldPos, (nodeDiameter - 0.02f) * new Vector3(1, 0.2f, 1));
            }
        }
    }

    //通過位置得到在哪一個格子
    public Node FindWithPosition(Vector3 position)
    {
        //在x方向的佔比
        float percentX = (position.x + gridSize.x / 2) / gridSize.x;
        float percentY = (position.z + gridSize.y / 2) / gridSize.y;

        //算出在哪個格子
        int x = Mathf.RoundToInt((gridContX - 1) * percentX);
        int y = Mathf.RoundToInt((gridContY - 1) * percentY);

        return grid[x, y];
    }

    //通過一個點尋找周圍的點
    public List<Node> GetAroundNode(Node node)
    {
        List<Node> aroundNodes = new List<Node>();

        for (int i = -1; i <= 1; i++)
        {
            for (int j = -1; j <= 1; j++)
            {
                //傳進來的點的下標  跳過
                if(i == 0 && j == 0)
                {
                    continue;
                }

                int tempX = node.gridX + i;
                int tempY = node.gridY + j;

                //判斷有沒有越界
                if (tempX >= 0 && tempX < gridContX && tempY >= 0 && tempY < gridContY)
                {
                    aroundNodes.Add(grid[tempX, tempY]);
                }
            }
        }

        return aroundNodes;
    }
}

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

public class FindPath_AStar : MonoBehaviour
{
    public Transform startPoint;
    public Transform endPoint;


    private Grid grid;
	// Use this for initialization
	void Start ()
    {
        grid = GetComponent<Grid>();

    }
	
	void Update ()
    {
        FindPath(startPoint.position, endPoint.position);

    }

    //
    void FindPath(Vector3 startPos, Vector3 endPos)
    {
        //開啟列表
        List<Node> opentSet = new List<Node>();
        //關閉列表
        List<Node> closeSet = new List<Node>();

        //起點格子
        Node startNode = grid.FindWithPosition(startPos);
        //終點格子
        Node endNode = grid.FindWithPosition(endPos);

        //把起點加入開啟列表
        opentSet.Add(startNode);

        //開始迴圈(開啟列表有值)
        while (opentSet.Count > 0)
        {
            //當前點
            Node currentNode = opentSet[0];
            //開啟列表中最小的f_Cost
            for (int i = 0; i < opentSet.Count; i++)
            {
                //如果總花費最小,並且離目標點最近
                if (opentSet[i].fCost <= currentNode.fCost && opentSet[i].hCost < currentNode.fCost)
                {
                    currentNode = opentSet[i];
                }
            }

            //把這個點 點紅
            //把當前點從開啟列表刪除
            opentSet.Remove(currentNode);
            //把當前點新增到關閉列表
            closeSet.Add(currentNode);

            //If當前點是終點,跳出迴圈
            if (currentNode == endNode)
            {
                GetPath(startNode, endNode);
                return;
            }

            //周圍的點
            List<Node> around = grid.GetAroundNode(currentNode);
            //迴圈周圍的點
            foreach (Node node in around)
            {
                //這個點不能走或者在關閉列表中,跳過這個點
                if (!node.canWalk || closeSet.Contains(node))
                {
                    continue;
                }
                //點開一個紅點,周圍的點會得到一個新的花費g
                int newCost_g = currentNode.gCost + GetCost(currentNode, node);
                //比較新花費和原來的花費,誰更小(誰離我們起點近) || 這個點不再開啟列表中
                if (newCost_g < node.gCost || !opentSet.Contains(node))
                {
                    //替換成新的花費
                    node.gCost = newCost_g;
                    node.hCost = GetCost(node, endNode);
                    //將這個點(周圍的點裡面的)的父節點設定為當前點(新點開的紅點)
                    node.parent = currentNode;

                    //這個點不再開啟列表中
                    if (!opentSet.Contains(node))
                    {
                        opentSet.Add(node);
                    }
                }
            }
        }
    }

    //計算花費
    int GetCost(Node a, Node b)
    {
        //等到兩點之間的一個距離(x方向和y方向)
        int coutX = Mathf.Abs(a.gridX - b.gridX);
        int coutY = Mathf.Abs(a.gridY - b.gridY);

        if(coutX > coutY)
        {
            return (coutX - coutY) * 10 + coutY * 14;
        }
        else
        {
            return (coutY - coutX) * 10 + coutX * 14;
        }
    }


    //得到路徑
    void GetPath(Node startNode, Node endNode)
    {
        List<Node> path = new List<Node>();
        Node temp = endNode;
        while(temp != startNode)
        {
            path.Add(temp);
            temp = temp.parent;
        }
        //列表轉置
        path.Reverse();
        grid.path = path;
    }
}