UnityA星寻路算法获取最短路径
~最后效果
1. 场景的搭建
2. 说明
A星寻路公式 F = G + H
F: 寻路消耗(越小说明距离终点越近)
G: 起点距离当前点的代价
H: 当前点距离终点的代价
脚本 | 说明 |
---|---|
Singleton | 继承该脚本实现单例 |
AStarNode | 存储每个节点的信息 |
AStarManager | 所有节点的管理器 |
Test | 使用节点管理器实现可视化的寻路流程 |
3. Singleton脚本
继承该脚本实现单例
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> where T : class
{
private static T instance;
public static T Instance
{
get
{
if(instance == null)
{
// 通过反射创建实例
instance = (T)Activator.CreateInstance(typeof(T), true);
}
return instance;
}
}
}
4. AStarNode脚本
存储每个节点的信息
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 节点的类型
public enum AStarNodeType
{
Walk, // 可以走的
NotWalk, // 障碍物
Start, // 起点
End, // 终点
}
public class AStarNode
{
// 节点坐标
public int x;
public int y;
// 寻路消耗
public float f;
// 离起点的代价
public float g;
// 离终点的代价
public float h;
// 父对象
public AStarNode father;
// 类型
public AStarNodeType type;
// 构造函数
public AStarNode(int x, int y, AStarNodeType type)
{
this.x = x;
this.y = y;
this.type = type;
}
}
5. AStarManager 脚本
所有节点的管理器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AStarManager : Singleton<AStarManager>
{
private AStarManager()
{
// 实例化开始列表和关闭列表
openList = new List<AStarNode>();
closeList = new List<AStarNode>();
}
// 地图宽高
private int w;
private int h;
// 存储所有节点的二维数组
public AStarNode[,] nodes;
// 开始列表
private List<AStarNode> openList;
// 关闭列表
private List<AStarNode> closeList;
// 初始化地图
public void InitMap(int w, int h)
{
// 获取地图宽高
this.w = w;
this.h = h;
// 实例化数组
nodes = new AStarNode[w, h];
// 遍历存储所有节点,并有百分之20几率是障碍物类型的节点
for (int i = 0; i < w; i++)
{
for(int j = 0<