A星算法

时间:2023-03-08 20:28:54
A星算法

没有采用二叉堆算法优化, 学习了几天终于搞除了一个demo, 这个列子如果点击按钮生成的方块大小不正确,可以先设置下预设调成相应的大小

只能上下左右走

A星算法

A星算法

 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System; public class AStar
{ public static PriorityQueue closedList;
public static PriorityQueue openList; public static List<Node> FindPath(Node start, Node goal)
{
closedList = new PriorityQueue();
openList = new PriorityQueue(); //初始化OpenList
openList.Push(start); //把开始节点放入OpenList中 start.F = 0;
start.G = 0;
start.H = NodeCost(start, goal); start.SetH(start.H);
start.SetF(start.F);
start.SetG(start.G); Node node = null;
List<Node> neighbours = null;
Node neighbourNode = null;
DateTime now = System.DateTime.Now; while (openList.Length != 0)
{
node = openList.First(); //如果是终点,就返回一个列表list过去
if (node.x == goal.x && node.y == goal.y)
{
Debug.Log("算法所消耗的时间: " + (System.DateTime.Now - now).TotalSeconds);
return CalculatePath(node);
} neighbours = new List<Node>();
GridManager.Instance.GetNeighbours(node, neighbours); //获取周围的格子加入列表中 //遍历周围的方块
for (int i = 0; i < neighbours.Count; i++)
{
neighbourNode = neighbours[i]; float newCost = node.G + TraverseCost(node,neighbourNode); //相邻的方块如果以前的G值小于 这次计算的G值就忽略该格子
if ((closedList.Contains(neighbourNode) || openList.Contains(neighbourNode)) && (neighbourNode.G <= newCost))
{
continue; }else{
neighbourNode.G = newCost;
neighbourNode.parent = node;
neighbourNode.H = NodeCost(neighbourNode, goal); //这个格子离终点的估算
neighbourNode.F = neighbourNode.G + neighbourNode.H; //显示H F G的值
neighbourNode.SetH(neighbourNode.H);
neighbourNode.SetF(neighbourNode.F);
neighbourNode.SetG(neighbourNode.G); //如果方块不在开启列表中,就添加到开启列表中
if (!openList.Contains(neighbourNode))
{
openList.Push(neighbourNode);
}
}
} //把寻找的节点放入关闭列表中
closedList.Push(node);
openList.Remove(node);
node.closeed = true;
} Debug.Log("算法所消耗的时间: " + (System.DateTime.Now - now).TotalMilliseconds); if (node.x != goal.x && node.y != goal.y)
{
Debug.LogError("没有找到路径");
return null;
} Debug.Log("找到路径了");
return CalculatePath(node);
} /// <summary>
/// 获取两个节点的距离(不计算障碍物)
/// </summary>
/// <param name="a">开始节点</param>
/// <param name="b">结束节点</param>
/// <returns>返回x +y 的距离</returns>
private static int NodeCost(Node a, Node b)
{
int x = (int)Mathf.Abs(b.x - a.x);
int y = (int)Mathf.Abs(b.y - a.y);
return x + y;
} /// <summary>
/// 获取最终路径
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static List<Node> CalculatePath(Node node)
{
List<Node> list = new List<Node>(); while (node != null)
{
list.Add(node);
node = node.parent;
}
list.Reverse();
return list;
} public static float TraverseCost(Node a,Node b)
{
if (b.xiejia)
{
b.xiejia = false;
return a.G + 1.4f;
}
else
{
return a.G + 1.0f;
}
} }

 

下载地址: http://yunpan.cn/ccS42whwzQ3Sy  访问密码 97d9