UnityA星寻路算法获取最短路径

本文介绍了在Unity游戏引擎中如何实现A*寻路算法来获取角色从起点到终点的最短路径。通过场景搭建、算法公式解析、Singleton脚本、AStarNode和AStarManager的详细说明,以及Test脚本的可视化演示,展示了A*寻路算法的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

~最后效果

在这里插入图片描述

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<
### Unity 中实现 A 寻路算法Unity 游戏开发中,为了使角色能够自动导航至指定的目标位置,通常会采用 A* 寻路算法。此算法不仅适用于简单的网格环境,还能处理复杂的地形特征,如障碍物、河流或沼泽等地形带来的额外成本。 #### 使用 A* Pathfinding Project 插件简化集成过程 对于商业项目而言,直接利用成熟的第三方库可以节省大量时间和精力。A\* Pathfinding Project 是一款专为 Unity 设计的高度优化的插件[^1]。这款工具提供了直观易用的界面来配置各种参数,并支持多种场景下的高效路径规划。 #### 自定义实现 A* 算法的关键要素 如果倾向于手动编码,则需理解几个核心概念: - **F = G + H**: 这是决定优先级队列中节点顺序的重要公式。其中 `G` 表示从起点到当前节点的实际开销;而 `H` 则是对剩余距离的一种估计值(通常是曼哈顿距离或欧几里得距离)。两者相加得到总的成本函数 `F`,用于指导搜索方向[^3]。 - **开放列表与关闭列表**: 开放列表存储待评估的新节点集合;一旦某个节点被完全分析完毕就会移入关闭列表,防止重复访问同一位置。 - **启发式估算 (Heuristic)**: 选择合适的启发式方法直接影响着最终结果的质量和效率。常见的选项有直线距离、切比雪夫距离等。 下面是一个简化的 Python 版本伪代码表示如何构建基本框架: ```python import heapq def a_star_search(graph, start, goal): frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 while not frontier.empty(): current = frontier.get() if current == goal: break for next in graph.neighbors(current): # 遍历邻居结点 new_cost = cost_so_far[current] + graph.cost(current, next) if next not in cost_so_far or new_cost < cost_so_far[next]: cost_so_far[next] = new_cost priority = new_cost + heuristic(goal, next) # 计算f(n)=g(n)+h(n) frontier.put(next, priority) came_from[next] = current return reconstruct_path(came_from, start, goal) def heuristic(a, b): """计算两点之间的直角坐标系中的绝对差之和作为近似""" (x1, y1) = a (x2, y2) = b return abs(x1 - x2) + abs(y1 - y2) class SimpleGraph(object): def __init__(self): self.edges = {} def neighbors(self, id): return self.edges[id] graph = SimpleGraph() # 定义图结构... ``` 上述例子展示了怎样创建一个简易版的 A* 搜索器,当然这只是一个非常基础的概念验证模型,在实际应用时还需要考虑更多细节问题,例如多层地图的支持、动态变化的地图数据更新机制等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值