AStar和JPS算法 以及Unity+tilemap实现

AStar算法

ASatr算法是Dijkstra算法的一种优化算法,Dijkstra每次找最近的中间点时,使用的是if(set[j] == 0 && dis[j] <min) ,直接拿中间点到起点的距离判断。A星将其优化为dis[j] + h[j] < min 增加了一个估值函数,计算中间点到终点的距离。
不同的估值函数影响了AStar算法的性能。
不错的介绍视频:A*寻路算法详解 #A星 #启发式搜索_哔哩哔哩_bilibili

有专门的A星寻路算法的实现库:
Get Started With The A* Pathfinding Project - A* Pathfinding Project (arongranberg.com)
【Astart寻路插件】Unity3d 寻路插件A*Pathfinding学习与研究_Unity3D软件工程师。的技术博客_51CTO博客

使用AStarPathfinding插件

添加一个空节点,增加Pathfinder组件
2. 修改Graphic设置在这里插入图片描述

  1. 在行动单位上添加组件 AILerp 和AIDestinationSetter,修改参数在这里插入图片描述
  2. 设置后场景图在这里插入图片描述

效果图:
在这里插入图片描述

我的unity + tilemap的实现

在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class APath : MonoBehaviour
{
    public Grid grid;
    public Tilemap road;
    public TileBase tilePathFlag;
    public TileBase TargetFlag;
    public TileBase PathFlag;
    public int start_x,start_y;
    public float DelayTime = 0.1f;
    int end_x,end_y;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            var worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            var cellPos = grid.WorldToCell(worldPos);
            end_x = cellPos.x;
            end_y = cellPos.y;
            road.SetTile(cellPos, TargetFlag);
            StartCoroutine(StartWalk());
        }
        if(Input.GetMouseButtonDown(1))
        {
            road.ClearAllTiles();
        }
    }
    List<Vector2Int> vector2s = new List<Vector2Int>
    {
        new Vector2Int(-1,0),
        new Vector2Int(1,0),
        new Vector2Int(0,1),
        new Vector2Int(0,-1)
    };
    Dictionary<int, Dictionary<int, int>> disMap = new Dictionary<int, Dictionary<int, int>>();
    Dictionary<int, Dictionary<int, int>> visitMap = new Dictionary<int, Dictionary<int, int>>();
    Dictionary<int, Dictionary<int, Vector3Int>> path = new Dictionary<int, Dictionary<int, Vector3Int>>();


    void AddVisit(int x,int y)
    {
        visitMap.TryGetValue(x, out var cells);
        if (cells == null)
        {
            visitMap[x] = new Dictionary<int, int>();
            cells = visitMap[x];
        }
        cells[y] = y;
    }

    bool InVisit(int x,int y)
    {
        visitMap.TryGetValue(x, out var cells);
        if (cells == null)
        {
            return false;
        }

        return cells.ContainsKey(y);
    }

    void AddPath(int tx,int ty, Vector3Int v)
    {
        path.TryGetValue(tx, out var cells);
        if (cells == null)
        {
            path[tx] = new Dictionary<int, Vector3Int>();
            cells = path[tx];
        }
        cells[ty] = v;
    }

    Vector3Int? GetPath(int x,int y)
    {
        path.TryGetValue(x, out var cells);
        if (cells == null)
        {
            return null;
        }
        cells.TryGetValue(y,out var v);
        return v;
    }
    //将xy邻接点加入备选列表
    bool AddTempCell(int x,int y,int dis)
    {
        foreach(var pos in vector2s)
        {
            int tx = x + pos.x;
            int ty = y + pos.y;
            var temp = new Vector3Int(tx, ty, 0);
            if(tx == end_x && ty == end_y)
            {
                AddPath(tx, ty, new Vector3Int(x, y, 0));
                return true;
            }
            if(road.GetTile(temp) == null)
            {
                disMap.TryGetValue(tx, out var cells);
                if(cells == null)
                {
                    disMap[tx] = new Dictionary<int, int>();
                    cells = disMap[tx];
                }
                if (cells.TryGetValue(ty, out var cell))
                {
                    if(cell > dis + 1)
                    {
                        cells[ty] = dis + 1;
                        AddPath(tx, ty, new Vector3Int(x, y, 0));
                    }
                }
                else
                {
                    cells[ty] = dis + 1;
                    AddPath(tx, ty, new Vector3Int(x, y, 0));
                }
            }
        }
        return false;
    }
    int ComputeDis(int x,int y)
    {
        var dis = Mathf.Abs(x-end_x) + Mathf.Abs(y-end_y);
        return dis;
    }
    IEnumerator StartWalk()
    {
        // 初始化
        disMap.Clear();
        visitMap.Clear();
        path.Clear();
        if (AddTempCell(start_x, start_y, 0))
        {
            DrawPath();
            yield break;
        }
        while (true)
        {
            // 寻找中间点
            int minDis = int.MaxValue;
            int minX = 0;
            int minY = 0;
            int targetV = 0;
            foreach(var cells in disMap)
            {
                foreach (var cell in cells.Value)
                {
                    int x = cells.Key;
                    int y = cell.Key;
                    if (InVisit(x, y)) continue;
                    int v = cell.Value;
                    int dis = (int)(v*0.1+0.9*ComputeDis(x, y));
                    if (dis < minDis)
                    {
                        minDis = dis;
                        minX = x;
                        minY = y;
                        targetV = v;
                    }
                }
            }
            AddVisit(minX, minY);
            road.SetTile(new Vector3Int(minX, minY,0), tilePathFlag);
            // 使用中间点更新disMap
            if (AddTempCell(minX, minY, targetV))
            {
                DrawPath();
                yield break;
            }
            yield return new WaitForSeconds(DelayTime);
        }
    }

    void DrawPath()
    {
        Vector3Int? pos = path[end_x][end_y];
        while(pos != null && (pos.Value.x != start_x || pos.Value.y != start_y))
        {
            road.SetTile(pos.Value, PathFlag);
            pos = GetPath(pos.Value.x, pos.Value.y);
        }
    }
}

JPS 跳点算法

A星的一种优化算法,主要思路是寻找路径中的拐点。

JPS/JPS+ 寻路算法 - KillerAery - 博客园 (cnblogs.com)
核心概念:

强迫邻居(Forced Neighbour)

强迫邻居:节点 x 的8个邻居中有障碍,且 x 的父节点 p 经过x 到达 n 的距离代价比不经过 x 到达的 n 的任意路径的距离代价小,则称 n 是 x 的强迫邻居。

看定义也许十分晦涩难懂。直观来说,实际就是因为前进方向(父节点到 x 节点的方向为前进方向)的某一边的靠后位置有障碍物,因此想要到该边靠前的空位有最短的路径,就必须得经过过 x 节点。

可能的情况见图示,黑色为障碍,红圈即为强迫邻居:

(左图为直线方向情况下的强迫邻居,右图为斜方向情况下的强迫邻居)

跳点(Jump Point)

跳点:当前点 x 满足以下三个条件之一:

  • 节点 x 是起点/终点。
  • 节点 x 至少有一个强迫邻居。
  • 如果父节点在斜方向(意味着这是斜向搜索),节点x的水平或垂直方向上有满足条件a,b的点。

节点y的水平或垂直方向是斜向向量的拆解,比如向量d=(1,1),那么水平方向则是(1,0),并不会往左搜索,只会看右边,如果向量d=(-1,-1),那么水平方向是(-1,0),只会搜索左边,不看右边,其他同理。

下图举个例子,由于黄色节点的父节点是在斜方向,其对应分解成向上和向右两个方向,因为在右方向发现一个蓝色跳点,因此黄色节点也应被判断为跳点:

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值