unity A星寻路教程

您所在的位置:网站首页 游戏地图转化为a星寻路地图怎么弄 unity A星寻路教程

unity A星寻路教程

2024-07-14 14:14| 来源: 网络整理| 查看: 265

核心代码

使用说明:

需要自行设置,地图数据,起点,终点

直接调用   AStarPath.FindPath  即可

 

using System.Collections; using System.Collections.Generic; using UnityEngine; /// /// A星寻路 /// public class AStarPath { /// /// 寻路 /// /// 地图数据 /// 起点 /// 终点 /// public static List FindPath(Point[,] map, Point start, Point end) { List openList = new List(); List closeList = new List(); openList.Add(start); while(openList.Count>0)//只要开放列表还存在元素就继续 { Point point = GetMinFOfList(openList);//选出open集合中F值最小的点 openList.Remove(point); closeList.Add(point); List SurroundPoints = GetSurroundPoint(map, point.X, point.Y); foreach(Point p in closeList)//在周围点中把已经在关闭列表的点删除 { if(SurroundPoints.Contains(p)) { SurroundPoints.Remove(p); } } foreach (Point p in SurroundPoints)//遍历周围的点 { if (openList.Contains(p))//周围点已经在开放列表中 { //重新计算G,如果比原来的G更小,就更改这个点的父亲 int newG = 1 + point.G; if(newG 0 && !map[x-1,y].isObstacle) { PointList.Add(map[x - 1, y]); } if(y > 0 && !map[x , y-1].isObstacle) { PointList.Add(map[x, y - 1]); } if(x < map.GetLength(0)-1 && !map[x + 1, y].isObstacle) { PointList.Add(map[x + 1, y]); } if(y < map.GetLength(1)-1 && !map[x , y+1].isObstacle) { PointList.Add(map[x, y + 1]); } return PointList; } //计算某个点的F值 static void GetF(Point point, Point end) { int G = 0; int H = Mathf.Abs(end.X - point.X) + Mathf.Abs(end.Y - point.Y); if(point.parent!=null) { G = 1 + point.parent.G; } int F = H + G; point.H = H; point.G = G; point.F = F; } //得到一个集合中F值最小的点 static Point GetMinFOfList(List list) { int min = int.MaxValue; Point point = null; foreach(Point p in list) { if(p.F0 && !map[x , y-1].isObstacle) { PointList.Add(map[x, y - 1]); } if(x


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3