算法 fCost = gCost + hCost
gCost 是当前节点到移动起始点的消耗,hCost是当前节点到终点的消耗
网格为变成为1的矩形,左右相邻的两个网格直接的gCost为1,斜对角相邻的两个网格的gCost为1.4
hCost 当前网格到终点网格的 水平距离 + 垂直距离
比如当前网格位置是(2,3),终点位置(10,8),则hCost = (10-2) + (8-3)
原始的算法是 fCost = gCost + hCost,均匀计算周围网格
对于一些比较复杂的散装障碍物场景,我们可以适当调整gCost和hCost的权重,比如 fCost = gCost x 4 + hCost x 6,这个修改会让寻路的时候,在消耗相同的网格点上,优先在距离终点位置更近的网格周围寻路。当我们从(1,1)向(3,10)位置寻路的时候,我们在店(3,1)和点(1,10)两个位置的 gCost + hCost 是相等的,但是点(1,10)其实距离终点更近一些,用调整过权重的算法,(1,10)我们得出来的的值会小一些,就可以优先从(1,10)位置寻找可移动路径

代码如下
寻路节点

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class AstarNode
{public int gridX;public int gridY;public Vector3 position;public float hCost;public float gCost;public float fCost {get{return gCost + hCost;}}/// <summary>/// 优先处理距离终点近的node/// </summary>public float fCostNew {get{return gCost*4 + hCost*6;}}public bool walkable;public AstarNode parent;public AstarNode(){}public AstarNode(int x, int y, Vector3 pos, bool canWalk){gridX = x;gridY = y;position = pos;walkable = canWalk;}}

地图网格生成

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using Random = System.Random;
public enum SearchType
{NeighborFour,NeighborEight,
}
public class MapGridsManager : MonoBehaviour
{public int width = 100;public int height = 100;public float cellSize = 1f;public Mesh mesh;private Vector3 originPoint;private AstarNode[,] grids;public AStartManager manager;public AstartMoveTest moveTarget;public bool isUseCache = false;public bool isUseNewCost = false;public SearchType searchType = SearchType.NeighborFour;[Header("障碍物生成范围") ]public Rect obstacleRect;void Awake(){originPoint = Vector3.zero;mesh = Resources.GetBuiltinResource<Mesh>("Quad.fbx");}private void Start(){grids = new AstarNode[width, height];Dictionary<int, AstarNode> nodeDic = GetCacheData();for (int i = 0; i < width; i++){for (int j = 0; j < height; j++){int keyId = i * 100000 + j;AstarNode node;if (isUseCache && nodeDic.ContainsKey(keyId)){node = nodeDic[keyId];}else{bool isObstacal = UnityEngine.Random.Range(1, 100) > 50;isObstacal = i >= obstacleRect.xMin && i < obstacleRect.xMax && j >= obstacleRect.yMin && j < obstacleRect.yMax  && isObstacal;bool warkAble = !isObstacal;node = new AstarNode(i, j, originPoint + new Vector3(i * cellSize, 0, j * cellSize), warkAble);    }grids[i, j] = node;}}serilizeNode();}void serilizeNode(){StringBuilder sb = new StringBuilder();for (int i = 0; i < width; i++){for (int j = 0; j < height; j++){var node = grids[i, j];int warkState = node.walkable ?1:0;if (i>0 || j > 0){sb.Append("|");}var data = $"{node.gridX}_{node.gridY}_{warkState}_{node.position.x}_{node.position.y}_{node.position.z}";sb.Append(data) ;}}string res = sb.ToString();UnityEngine.PlayerPrefs.SetString("grid_data", res);}Dictionary<int, AstarNode> GetCacheData(){Dictionary<int, AstarNode> nodeDic = new Dictionary<int, AstarNode>(width * height);string data = UnityEngine.PlayerPrefs.GetString("grid_data", "");string[] arr = data.Split("|");for (int i = 0; i < arr.Length; i++){string itemStr = arr[i];string[] itemArr = itemStr.Split("_");if (itemArr.Length < 6){continue;}AstarNode node = new AstarNode();node.gridX = int.Parse(itemArr[0]);node.gridY = int.Parse(itemArr[1]);node.walkable = int.Parse(itemArr[2]) == 1 ? true : false;float positionX = float.Parse(itemArr[3]);float positionY = float.Parse(itemArr[4]);float positionZ = float.Parse(itemArr[5]);node.position = new Vector3(positionX, positionY, positionZ);int keyId = node.gridX * 100000 + node.gridY;nodeDic.Add(keyId, node);}return nodeDic;}public AstarNode GetNode(int x, int y){if (x < 0 || x >= width || y < 0 || y >= height){return null;}return grids[x, y];}public List<AstarNode> GetNeighborNodes(AstarNode node){if (searchType == SearchType.NeighborFour)return GetNeighborFourNodes(node);else{return GetNeighborEightNodes(node);}}public List<AstarNode> GetNeighborFourNodes(AstarNode node){List<AstarNode> nodeList = new List<AstarNode>();int nodeX = node.gridX;int nodeY = node.gridY;for (int i = -1; i <= 1; i++){for (int j = -1; j <= 1; j++){if (i == 0 && j == 0){continue;}if (i == 0 || j == 0){int itemX = nodeX + i;int itemY = nodeY + j;AstarNode itemNode = GetNode(itemX, itemY);if (itemNode != null){nodeList.Add(itemNode);}}}}return nodeList;}public List<AstarNode> GetNeighborEightNodes(AstarNode node){List<AstarNode> nodeList = new List<AstarNode>();int nodeX = node.gridX;int nodeY = node.gridY;for (int i = -1; i <= 1; i++){for (int j = -1; j <= 1; j++){if (i == 0 && j == 0){continue;}int itemX = nodeX + i;int itemY = nodeY + j;AstarNode itemNode = GetNode(itemX, itemY);if (itemNode != null){nodeList.Add(itemNode);}}}return nodeList;}public AstarNode GetByWorldPositionNode(Vector3 pos){int x = Mathf.FloorToInt(pos.x / cellSize);int y = Mathf.FloorToInt(pos.y / cellSize);if (x < 0 || y < 0 || x>=width || y >= height){return null;}return grids[x, y];}void OnDrawGizmos(){Gizmos.color = Color.gray;if (grids != null){for (int i = 0; i < width; i++){for (int j = 0; j < height; j++){AstarNode node = grids[i, j];if (manager != null){if (manager.rodeList.Contains(node)){Gizmos.color = Color.white;}else if(manager.openList.Contains(node)){Gizmos.color = Color.black;}else if (manager.closeList.Contains(node)){Gizmos.color = Color.green;}else{Gizmos.color = node.walkable?  Color.blue: Color.red;}if (manager.moveEndNode != null && manager.moveEndNode == node){Gizmos.color = Color.yellow;}if (manager.moveStartNode != null && manager.moveStartNode == node){Gizmos.color = Color.gray;}}else{Gizmos.color = node.walkable?  Color.blue: Color.red;}// Gizmos.DrawCube(node.position, Vector3.one);var rotation = Quaternion.Euler(new Vector3(90, 0, 0));Gizmos.DrawMesh(mesh, node.position, rotation, Vector3.one);}}}Gizmos.color = Color.black;var halfCellSize = cellSize / 2;for (int i = 0; i <= width; i++){Gizmos.DrawLine(new Vector3(i-halfCellSize,0,0), new Vector3(i-halfCellSize, 0 ,height-halfCellSize));}for (int i = 0; i <= height; i++){Gizmos.DrawLine(new Vector3(0,0,i-halfCellSize), new Vector3(width-halfCellSize, 0 ,i-halfCellSize));}}public void ResetNodeCost(){for (int i = 0; i < width; i++){for (int j = 0; j < height; j++){var node = grids[i, j];node.gCost = 0;node.hCost = 0;}}}public void BeginMove(List<AstarNode> rodeNodeList){moveTarget.BeginMove(rodeNodeList);}
}

寻路

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;[Serializable]
public class ObstacleRange
{public int x;
}
public class AStartManager : MonoBehaviour
{public MapGridsManager map;public Vector3 from;public Vector3 end;public List<AstarNode> openList = new List<AstarNode>();public List<AstarNode> closeList = new List<AstarNode>();public List<AstarNode> rodeList = new List<AstarNode>();public AstarNode moveStartNode;public AstarNode moveEndNode;private bool isInFindPath = false;//是否正在训练中void Update(){if (Input.GetKeyUp(KeyCode.A)){StartCoroutine(FindPath(from, end));}else if(Input.GetMouseButtonDown(0)){Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);RaycastHit hit;if (Physics.Raycast(ray, out hit)){var pos = new Vector3(hit.point.x, hit.point.z, 0);Debug.Log($"{pos}--{Input.mousePosition}");var node = map.GetByWorldPositionNode(pos);if (node != null){ from = end;end =  pos;StartCoroutine(FindPath(from, end));}}}}void DoMove(){map.BeginMove(rodeList);}IEnumerator FindPath(Vector3 startPos, Vector3 endPos){if (isInFindPath){yield break;}isInFindPath = true;ResetNodeData();AstarNode startNode = map.GetByWorldPositionNode(startPos);startNode.gCost = 0;startNode.hCost = 0;startNode.parent = null;AstarNode endNode = map.GetByWorldPositionNode(endPos);endNode.gCost = 0;endNode.hCost = 0;endNode.parent = null;openList.Add(startNode);moveStartNode = startNode;moveEndNode = endNode;if (!endNode.walkable){Debug.LogError("终点不可抵达");isInFindPath = false;yield break;}int index = 0;while (openList.Count > 0){var targetNode = openList[0];Debug.Log($"{index}: ({targetNode.gridX} ,{targetNode.gridY})");openList.Remove(targetNode);if (targetNode.gridX == endNode.gridX && targetNode.gridY == endNode.gridY){GenerateRote(targetNode);openList.Clear();break;}AddOpenList(targetNode, endNode);if (map.isUseNewCost){openList.Sort((a, b)=>{return a.fCostNew.CompareTo(b.fCostNew);});}else{openList.Sort((a, b)=>{return a.fCost.CompareTo(b.fCost);});}yield return new WaitForSeconds(0.1f);index++;if (index > 5000){Debug.LogError("循环超出上限");break;}}Debug.Log("寻路循环次数为:" + index);DoMove();isInFindPath = false;}void ResetNodeData(){openList.Clear();closeList.Clear();rodeList.Clear();map.ResetNodeCost();}private bool AddOpenList(AstarNode targetNode, AstarNode endNode){var neighborNodes = map.GetNeighborNodes(targetNode);closeList.Add(targetNode);foreach (var item in neighborNodes){if (item.walkable == false || closeList.Contains(item) || openList.Contains(item)){continue;}float tempGCost = targetNode.gCost + GetDestance(targetNode, item);if (item.gCost <= 0 || tempGCost < item.gCost){item.parent = targetNode;item.gCost = targetNode.gCost + GetDestance(targetNode, item);item.hCost = Mathf.Abs(endNode.gridX - item.gridX) + Mathf.Abs(endNode.gridY - item.gridY);openList.Add(item);}}return false;}List<AstarNode> GenerateRote(AstarNode curNode){rodeList = new List<AstarNode>();rodeList.Add(curNode);while (curNode.parent != null){curNode = curNode.parent;rodeList.Add(curNode);}rodeList.Reverse();return rodeList;}float GetDestance(AstarNode node1, AstarNode node2){float distance  ;if (node1.gridX != node2.gridX && node1.gridY != node2.gridY){distance = 1.4f;}else{distance = 1f;}return distance; }
}

控制对象在路径点移动

using System.Collections.Generic;
using UnityEngine;public class AstartMoveTest : MonoBehaviour
{public Transform moveTarget;//移动对象private List<AstarNode> rodeNodeList;//行走路径点private int moveIndex;//当前移动到第几个点private bool isMoveing = false;//是否正在移动过程中private float miniDistance = 0.1f;private Vector3 endPosition;private Vector3 moveDir;public float speed = 1;// Start is called before the first frame updatevoid Start(){}public void BeginMove(List<AstarNode> rodeNodeList){if (rodeNodeList == null || rodeNodeList.Count < 2){Debug.LogError("路径点异常,无法开始移动");return;}this.rodeNodeList = rodeNodeList;transform.position = rodeNodeList[0].position;isMoveing = true;moveIndex = 1;endPosition = rodeNodeList[moveIndex].position;moveDir = rodeNodeList[moveIndex].position - rodeNodeList[0].position;moveDir = moveDir.normalized;}// Update is called once per framevoid Update(){if (!isMoveing){return;}float distance = Vector3.Distance(transform.position, endPosition);// Debug.Log("distance = " + distance);if (distance < miniDistance){moveIndex++;if (moveIndex >= rodeNodeList.Count){isMoveing = false;Debug.Log("移动结束");return;}endPosition = rodeNodeList[moveIndex].position;transform.LookAt(endPosition);moveDir = endPosition - transform.position;moveDir = moveDir.normalized;}// transform.position = Vector3.Lerp(transform.position, endPosition, speed*Time.deltaTime);transform.position = transform.position + moveDir * Time.deltaTime * speed;}
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

网格是用Gizmos中绘制的,需要调整为top视图
图中黄色网格是终点,灰色网格是起始点,白色是寻路结果,红色是障碍物点
在这里插入图片描述

资源下载地址 demo链接

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/88273.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/88273.shtml
英文地址,请注明出处:http://en.pswp.cn/pingmian/88273.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

十一 Javascript的按值传递

你将知道&#xff1a;“传递” 值是什么意思什么是按值传递传递物品JavaScript 中没有传递引用&#xff01;介绍当需要在 JavaScript 中分配或简单地将一个值传递给其他标识符时&#xff0c;我们就会看到通常所说的 按值传递 。严格来说&#xff0c;JavaScript 中传递值的方式只…

SpringBoot ThreadLocal 全局动态变量设置

需求说明&#xff1a; 现有一个游戏后台管理系统&#xff0c;该系统可管理多个大区的数据&#xff0c;但是需要使用大区id实现数据隔离&#xff0c;并且提供了大区选择功能&#xff0c;先择大区后展示对应的数据。需要实现一下几点&#xff1a; 1.前端请求时&#xff0c;area_i…

如何解决pip安装报错ModuleNotFoundError: No module named ‘logging’问题

【Python系列Bug修复PyCharm控制台pip install报错】如何解决pip安装报错ModuleNotFoundError: No module named ‘logging’问题 摘要&#xff1a; 在使用 PyCharm 2025 控制台通过 pip install 安装第三方库时&#xff0c;常会遇到诸如 ModuleNotFoundError: No module name…

打破技术债困境:从“保持现状”到成为变革的推动者

相信许多在科技行业的同行都面临过类似的挑战&#xff1a;明知系统存在“技术债”&#xff0c;却因为沟通成本、团队压力和短期KPI等原因&#xff0c;难以推动改进&#xff0c;最终陷入“想做却不敢做”的矛盾心态。这不仅影响个人心情&#xff0c;更重要的是&#xff0c;它像一…

Spring Boot 整合 RabbitMQ

Spring Boot 整合 RabbitMQ 一、概述&#xff1a;RabbitMQ 是什么&#xff1f; 你可以把 RabbitMQ 想象成一个「快递中转站」。 比如你在网上买了一本书&#xff0c;卖家&#xff08;生产者&#xff09;把包裹&#xff08;消息&#xff09;交给快递站&#xff08;RabbitMQ&…

Unity Demo-3DFarm详解-其一

我们来拆解一个种田游戏&#xff0c;这个游戏种类内部的功能还是比较模板化的&#xff0c;我们来一点点说。我们大体上分为这么几个部分&#xff1a;农场运营玩法角色与玩家互动物品与背包存档和进度管理用户界面系统农场运营可以大体上分为&#xff1a;种植系统&#xff1a;支…

esp8266驱动下载

问题描述&#xff1a;esp8266插上电脑&#xff0c;设备管理器无法识别&#xff0c;显示为USB serial&#xff08;黄色感叹号&#xff09; 首先确认你的esp8266是不是 CH340 系列的 USB 转串口芯片 CH340驱动下载地址

大语言模型的极限:知识、推理与创造力的边界探析

大语言模型的极限&#xff1a;知识、推理与创造力的边界探析 人工智能领域的快速发展推动了大语言模型&#xff08;LLM&#xff09;的广泛应用&#xff0c;这些模型在文本生成、知识问答和创意表达等方面展现出前所未有的能力。然而&#xff0c;随着应用场景的深化&#xff0c;…

git中的fork指令解释

在Git中&#xff0c;Fork 是指将他人的代码仓库&#xff08;Repository&#xff09;复制到自己的账户下&#xff0c;创建一个完全独立的副本[1][2]。以下是关于Fork的详细说明&#xff1a; Fork的定义与核心作用 定义&#xff1a;Fork是代码托管平台&#xff08;如GitHub&#…

iPhone 抓包工具有哪些?多工具对比分析优缺点

iOS 平台一向以安全性著称&#xff0c;这也使得对其进行网络调试和抓包变得异常困难。相比安卓&#xff0c;iPhone 抓包难点主要在以下几点&#xff1a; 系统限制代理设置的灵活性无法自由安装根证书抓包常涉及 HTTPS 解密与双向认证破解普通用户设备无 root 或越狱权限 因此&a…

使用 libcu++ 库

文章目录使用 libcu 库安装与设置基本组件1. 原子操作2. 内存管理3. 类型特性4. 同步原语编译选项注意事项使用 libcu 库 libcu 是 NVIDIA 提供的 CUDA C 标准库实现&#xff0c;它为 CUDA 开发者提供了类似 C 标准库的功能和接口。以下是使用 libcu 的基本指南&#xff1a; …

[Leetcode] 预处理 | 多叉树bfs | 格雷编码 | static_cast | 矩阵对角线

魔术排列模拟一个特定的洗牌过程&#xff0c;并找到使得经过一系列洗牌和取牌操作后&#xff0c;能够与给定的目标数组target相匹配的最小k值核心思想: 预处理初始排列&#xff1a;从一个按顺序排列的数组&#xff08;例如&#xff0c;{1, 2, 3, ..., n}&#xff09;开始。洗牌…

【技术追踪】SynPo:基于高质量负提示提升无训练少样本医学图像分割性能(MICCAI-2025)

SAM 新用法&#xff0c;无需训练&#xff0c;利用高质量负提示提升分割性能~ 论文&#xff1a;SynPo: Boosting Training-Free Few-Shot Medical Segmentation via High-Quality Negative Prompts 代码&#xff1a;https://liu-yufei.github.io/synpo-project-page/ 0、摘要 大…

深入理解机器学习

一.前言本章节开始来讲解一下机器学习的知识&#xff0c;本期作为一个了解就大概介绍一下&#xff0c;我们不会从机器学习基础开始介绍&#xff0c;但是后面会来补充&#xff0c;随着ai的不断发展&#xff0c;机器学习在ai的领域里面的占比越来约少&#xff0c;我们还是以应用为…

数据结构 顺序表(1)

目录 1.线性表 2.顺序表 1.线性表 线性表&#xff08;linear list&#xff09;是n个具有相同特性的数据元素的有限序列。线性表是一种在实际中广泛使用 的数据结构&#xff0c;常见的线性表&#xff1a;顺序表、链表、栈、队列、字符串… 线性表在逻辑上是线性结构&#…

openssl 生成国密证书

openssl生成证书生成CA私钥 openssl ecparam -genkey -name SM2 -out ca.key.pem -noout证书请求 openssl req -new -key ca.key.pem -out ca.cert.req -subj “/CNrtems-strongswan-CA”生成证书 openssl x509 -req -days 3650 -in ca.cert.req -signkey ca.key.pem -out ca.c…

系统架构设计师论文分享-论分布式事务技术及其应用

我的软考历程 摘要 2023年9月&#xff0c;我所在的公司通过了研发纱线MES系统的立项&#xff0c;该系统为国内纱线工厂提供SAAS服务&#xff0c;旨在提高纱线工厂的数字化和智能化水平。我在该项目中担任系统架构设计师一职&#xff0c;负责该项目的架构设计工作。本文结合我…

东土科技智能塔机系统亮相南京,助力智能建造高质量发展

近日&#xff0c;由南京市城乡建设委员会、江苏省土木建筑学会主办的“无人驾驶智能塔机观摩会”&#xff0c;在中建三局一公司南京扬子江智慧中心项目现场成功举办。作为全国首批智能建造试点城市&#xff0c;南京市已出台20余项支持政策&#xff0c;落地93个试点项目&#xf…

3D Surface Reconstruction with Enhanced High-Frequency Details

3D Surface Reconstruction with Enhanced High-Frequency Details核心问题&#xff1a;当前基于神经隐式表示&#xff08;如 NeuS&#xff09;的 3D 表面重建方法&#xff0c;通常采用随机采样策略。这种随机采样难以充分捕捉图像中的高频细节区域&#xff08;如纹理、边缘、光…

Science Robotics 耶鲁大学开源视触觉新范式,看出机器人柔性手的力感知

摘要&#xff1a;在机器人视触觉传感领域&#xff0c;如何兼顾成本与性能始终是一大挑战。耶鲁大学在《Science Robotics》上发表最新研究&#xff0c;提出了一种“Forces for Free”&#xff08;F3&#xff09;新范式。该研究通过观测一个经过特殊优化的开源柔性手&#xff08…