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

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

~最后效果

在这里插入图片描述

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<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值