A*算法

A*算法的解释网上也有很多,可以百度看看,这里做下笔记

先上A*算法的伪代码:

 Node.cs用来存储每一个Node的信息

using UnityEngine;
using System.Collections;

public class Node {
    public bool _canWalk;//是否可以行走
    public Vector3 _worldPos;//世界坐标

    public int gridX;//二维数组的x坐标
    public int gridY;//二维数组的y坐标

    public Node parentNode;//父节点

    public int gCost;//起始点到当前点的距离
    public int hCost;//当前点到目标点的距离

    public int fCost {
        get {
            return gCost + hCost;
        }
    }

    public Node(bool CanWalk,Vector3 WorldPos,int x,int y) {
        this._canWalk = CanWalk;
        this._worldPos = WorldPos;
        this.gridX = x;
        this.gridY = y;
    }
}

Grid.cs用来初始化一些信息,并绘制出来

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

public class Grid : MonoBehaviour {

    private Node[,] grid;

    public Vector2 gridSize;//地图大小

    public float nodeRadius;//node半径
    public float nodeDiameter;//node直径

    public LayerMask whatLayer;//忽略的层 哪些不能行走

    public int gridCountX;//x轴的node数
    public int gridCountY;//y轴的node数

    public Transform player;

    public List<Node> path = new List<Node>();//路径集合

	// Use this for initialization
	void Start () {
        nodeDiameter = nodeRadius * 2;

        gridCountX = Mathf.RoundToInt(gridSize.x / nodeDiameter);
        gridCountY = Mathf.RoundToInt(gridSize.y / nodeDiameter);

        grid = new Node[gridCountX, gridCountY];

        CreateGrid();
    }
    /// <summary>
    /// 初始化信息,
    /// </summary>
    void CreateGrid() {
        Vector3 startPos = transform.position - gridSize.x * 0.5f * Vector3.right - gridSize.y * 0.5f * Vector3.forward;

        for (int i = 0; i < gridCountX; i++) {
            for (int j = 0; j < gridCountY; j++) {
                Vector3 worldPos = startPos + Vector3.right * (i * nodeDiameter + nodeRadius) + Vector3.forward * (j * nodeDiameter + nodeRadius);

                bool canWalk = !Physics.CheckSphere(worldPos, nodeRadius, whatLayer);

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

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireCube(transform.position, new Vector3(gridSize.x, 1, gridSize.y));

        if (grid == null)
            return;

        //画出哪些可以行走,哪些不能行走
        foreach (var node in grid) {
            Gizmos.color = node._canWalk ? Color.white : Color.red;
            Gizmos.DrawCube(node._worldPos, Vector3.one * (nodeDiameter - 0.1f));
        }

        Node playerNode = GetNodeFromPosition(player.position);

        //画出路径点
        if (path != null) {
            foreach (Node node in path) {
                Gizmos.color = Color.black;

                Gizmos.DrawCube(node._worldPos, Vector3.one * (nodeDiameter - 0.1f));
            }
        }

        if (playerNode != null && playerNode._canWalk) {
            Gizmos.color = Color.blue;
            Gizmos.DrawCube(playerNode._worldPos, Vector3.one * (nodeDiameter - 0.1f));
        }
    }
    /// <summary>
    /// 根据位置获取node
    /// </summary>
    /// <param name="pos"></param>
    /// <returns></returns>
    public Node GetNodeFromPosition(Vector3 pos) {
        float precentX = (pos.x + gridSize.x * 0.5f) / gridSize.x;
        float precentY = (pos.z + gridSize.y * 0.5f) / gridSize.y;

        precentX = Mathf.Clamp01(precentX);
        precentY = Mathf.Clamp01(precentY);

        int x = Mathf.RoundToInt((gridCountX - 1) * precentX);
        int y = Mathf.RoundToInt((gridCountY - 1) * precentY);

        return grid[x, y];
    }
    /// <summary>
    /// 获取给定Node的邻居节点
    /// </summary>
    /// <param name="node"></param>
    /// <returns></returns>
    public List<Node> GetNeibourhood(Node node) {
        List<Node> neibourhood = new List<Node>();

        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                if (i == 0 && j == 0) {
                    continue;
                }

                int tmpX = node.gridX + i;
                int tmpY = node.gridY + j;

                if (tmpX > 0 && tmpX < gridCountX && tmpY > 0 && tmpY < gridCountY) {

                    neibourhood.Add(grid[tmpX, tmpY]);
                }
            }
        }

        return neibourhood;
    }
}

FindPath.cs用来查找最短路径

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

public class FindPath : MonoBehaviour {

    private Grid grid;

    public Transform player;
    public Transform target;

	// Use this for initialization
	void Start () {
        grid = GetComponent<Grid>();
	}
	
	// Update is called once per frame
	void Update () {
        FindingPath(player.position, target.position);
	}

    void FindingPath(Vector3 startPos,Vector3 endPos) {
        Node startNode = grid.GetNodeFromPosition(startPos);
        Node endNode = grid.GetNodeFromPosition(endPos);
        List<Node> openList = new List<Node>();
        List<Node> closeList = new List<Node>();

        openList.Add(startNode);

        while (openList.Count > 0) {
            Node currentNode = openList[0];

            for (int i = 0; i < openList.Count; i++) {
                if (openList[i].fCost < currentNode.fCost ||
                    openList[i].fCost == currentNode.fCost && openList[i].hCost < currentNode.hCost) {
                    currentNode = openList[i];
                }
            }

            openList.Remove(currentNode);
            closeList.Add(currentNode);

            if (currentNode == endNode) {
                GeneratePath(startNode, endNode);
                break;
            }

            foreach (Node node in grid.GetNeibourhood(currentNode)) {
                if (node._canWalk == false || closeList.Contains(node))
                    continue;

                int newCost = currentNode.gCost + GetDistanceNodes(currentNode, node);

                if (newCost < node.gCost || openList.Contains(node) == false) {
                    node.gCost = newCost;
                    node.hCost = GetDistanceNodes(currentNode, endNode);
                    node.parentNode = currentNode;

                    if (openList.Contains(node) == false) {
                        openList.Add(node);
                    }
                }
            }
        }
    }
    /// <summary>
    /// 获取路径list
    /// </summary>
    /// <param name="startNode"></param>
    /// <param name="endNode"></param>
    private void GeneratePath(Node startNode,Node endNode)
    {
        List<Node> neibourhood = new List<Node>();

        Node tempNode = endNode;

        while (tempNode != startNode) {
            neibourhood.Add(tempNode);

            tempNode = tempNode.parentNode;
        }

        neibourhood.Reverse();

        grid.path = neibourhood;
    }
    /// <summary>
    /// 获取两个Node的距离
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    public int GetDistanceNodes(Node a, Node b)
    {
        int tempX = Mathf.Abs(a.gridX - b.gridX);
        int tempY = Mathf.Abs(a.gridY - b.gridY);

        if (tempX > tempY)
        {
            return 14 * tempY + 10 * (tempX - tempY);
        }
        else
        {
            return 14 * tempX + 10 * (tempY - tempX);
        }
    }
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值