C#实现Astar 算法以及导航系统

首先来说一下 Astar 是什么,它是寻求两个点之间一条最优路径 。但可能并不是最短路径.
要找地图上的一个点你就需要一个地图,而且把地图分成一个个格子,每个格子都有自己的信息

每个地图格子身上的类


//格子类型
public enum E_Type_Node
{//可行走区域walk,//不可走区域stop
}//格子类
public class AstarNode
{//格子坐标public int x, y;public float f;//寻路消耗public float g;//起点距离消耗public float h;//终点距离消耗public AstarNode father;//父对象public E_Type_Node type;//格子类型public AstarNode(int x,int y,E_Type_Node type){this. x = x;this.y = y;this.type = type;}
}

AstarMgr

这里 实现了 A星 找到了路径点

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Singletion<T> where T : class, new()
{static T ins;public static T Ins{get{if (ins == null){ins = new T();}return ins;}}
}// A星寻路管理器
public class AstarMgr : Singletion<AstarMgr>
{//所有格子对象public AstarNode[,] nodes;//打开private List<AstarNode> OpenList=new List<AstarNode>();//关闭private List<AstarNode> CloseList= new List<AstarNode>();//地图的 x,y 宽高private int Mapw;private int Maph;public void InitMapInfo(int w, int h){this.Mapw = w;this.Maph = h;//声明容器 的长度nodes = new AstarNode[w, h];AstarNode node;for (int i = 0; i < w; i++){for (int j = 0; j < h; j++){//只是为了测试node = new AstarNode(i, j, Random.Range(0, 100) < 20 ? E_Type_Node.stop : E_Type_Node.walk);nodes[i, j] = node;}}}/// <summary>/// 寻找路径/// </summary>/// <param name="startPos">开始坐标</param>/// <param name="endPos">结束坐标 </param>/// <returns></returns>public List<AstarNode> FindPath(Vector2 startPos, Vector2 endPos){//1.是否在地图范围内if (startPos.x < 0 || startPos.x >= Mapw || startPos.y < 0 || startPos.y >= Maph || endPos.x < 0 || endPos.x >= Mapw || endPos.y < 0 || endPos.y >= Maph){Debug.Log("不在地图范围内");return null;}AstarNode start = nodes[(int)startPos.x, (int)startPos.y];AstarNode end = nodes[(int)endPos.x, (int)endPos.y];//2.判断格子是否阻挡if (start.type == E_Type_Node.stop || end.type == E_Type_Node.stop){Debug.Log("开始或结束点是阻挡");return null;}//清空上一次寻路数据// 清空关闭和寻路列表OpenList.Clear();CloseList.Clear();// 把开始点放入关闭列表中start.father = null;start.f = 0;start.g = 0;start.h = 0;CloseList.Add(start);while (true){//从起点开始找周围的点并放入开启列表中///左上x -1 y - 1FindNearNodeToOpenList(start.x - 1, start.y - 1, 1.4f, start, end);//上 x y-1FindNearNodeToOpenList(start.x, start.y - 1, 1, start, end);//右上 x+1,y-11FindNearNodeToOpenList(start.x + 1, start.y - 1, 1.4f, start, end);//左 x-1,yFindNearNodeToOpenList(start.x - 1, start.y, 1f, start, end);//右 x,y-1;FindNearNodeToOpenList(start.x + 1, start.y, 1f, start, end);//左下 x-1,y+1FindNearNodeToOpenList(start.x - 1, start.y + 1, 1.4f, start, end);//下 x,y+1FindNearNodeToOpenList(start.x, start.y + 1, 1, start, end);//右下 x+1,y+1FindNearNodeToOpenList(start.x + 1, start.y + 1, 1.4f, start, end);//死路判断 开启列表为空 就是死路if (OpenList.Count == 0){Debug.Log("死路");return null;}// 选择 寻路消耗最小的点OpenList.Sort(SotrOpenList);//放入关闭列表中CloseList.Add(OpenList[0]);start = OpenList[0];OpenList.RemoveAt(0);if (start == end){//找到重点List<AstarNode> path = new List<AstarNode>();path.Add(end);while (end.father!=null){path.Add(end.father);end = end.father;}//反转path.Reverse();return path;}}}private int SotrOpenList(AstarNode a, AstarNode b){if (a.f > b.f){return 1;}elsereturn -1; }/// <summary>/// 计算临近点 是否可以放入Open List/// </summary>/// <param name="x"></param>/// <param name="y"></param>/// <param name="g"></param>/// <param name="father"></param>private void FindNearNodeToOpenList(int x, int y, float g, AstarNode father, AstarNode end){//判断边界if (x < 0 || x >= Mapw || y < 0 || y >= Maph){Debug.Log("不在地图范围内");return;}//在范围内 取点AstarNode node = nodes[x, y];if (node == null || node.type == E_Type_Node.stop||CloseList.Contains(node)||OpenList.Contains(node)){return;}//计算寻路消耗//记录父对象node.father = father;//计算g 我的开始距离= 我父亲的距离 +我的距离node.g = father.g = g;node.h = Mathf.Abs(end.x - node.x) + Mathf.Abs(end.y - node.y);node.f = node.g + node.h;//通过了上面 的验证,存入开启列表OpenList.Add(node);}
}

NavAgent( 导航实现类)

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;public class NavAgent : MonoBehaviour
{//速度private float speed;//路径的集合private Vector3[] roads;// 回掉private UnityAction endFunc;//当前路径点下标private int nextIndex = 0;private float totalTime;private float passedTime;private float vx, vy, vz;private bool isWalking;private Quaternion dstRot;public void Init() {}public void NavOnRoad(float speed, Vector3[] roads, UnityAction endFunc) {// step1: 准备数据,验证数据的合法性;this.speed = speed;this.roads = roads;this.endFunc = endFunc;if (this.roads.Length < 2) { return;}// step1: 将我们的角色放到起点,调整好初始方向this.transform.position = this.roads[0];this.transform.LookAt(this.roads[1]);// end// step2: 下一个点数据相关this.nextIndex = 1;this.WalkToNext();// end}// 走向nextIndexprivate void WalkToNext(){if (this.nextIndex >= this.roads.Length) { // 走到了尽头;this.isWalking = false;if (this.endFunc != null) {this.endFunc();}return;}// 从当前点走到下一个点Vector3 src = this.transform.position;Vector3 dst = this.roads[this.nextIndex];Vector3 dir = dst - src;float len = dir.magnitude;if (len <= 0) {this.nextIndex++;this.WalkToNext();return;}this.totalTime = len / this.speed;this.passedTime = 0;// end// 分解速度this.vx = this.speed * dir.x / len;this.vy = this.speed * dir.y / len;this.vz = this.speed * dir.z / len;// end// 调整角色的朝向Quaternion old = this.transform.rotation;this.transform.LookAt(dst);this.dstRot = this.transform.rotation;this.transform.rotation = old;// endthis.isWalking = true;}public void StopNav() { }public void GoAheadOnRoad() { }private void Update() {if (this.isWalking == false) {return;}// 更新移动的时间float dt = Time.deltaTime;this.passedTime += dt;if(this.passedTime > this.totalTime) {dt -= (this.passedTime - this.totalTime);}// end// 每次Update更新位置Vector3 pos = this.transform.position;pos.x += this.vx * dt;pos.y += this.vy * dt;pos.z += this.vz * dt;this.transform.position = pos;// 转向插值this.transform.rotation = Quaternion.Slerp(this.transform.rotation, this.dstRot, 8.0f * dt);// endif (this.passedTime >= this.totalTime) {this.nextIndex++;this.WalkToNext();}}
}

C#实现Astar 算法以及导航系统相关推荐

  1. A-Star算法探索和实现(一)

    什么是A-Star算法? A*搜寻算法俗称A星算法,又叫A-Star算法.A*算法是比较流行的启发式搜索算法之一,被广泛应用于路径优化领域(引用自百度百科).在游戏开发中,我们可以将A*算法作为一种敌 ...

  2. 利用Astar算法实现飞行轨迹的三维规划(基于Matlab代码实现)

    目录  1 概述     1.1研究背景  2 运行结果  3 Matlab代码实现  4 参考文献 1 概述 随着自动化技术的发展,现代航空技术水平有了前所未有的提高,促进了无人机在军事.民用领域的 ...

  3. 四足机器人运动运动控制系统及相关算法、导航系统及相关算法本人硕毕论文发表后再更

    四足机器人运动运动控制系统及相关算法.导航系统及相关算法本人硕毕论文发表后再更

  4. unity学习:寻路算法(AStar算法)与简单AI(势能场估价算法)

    项目地址:https://github.com/kotomineshiki/AIFindPath 视频地址:多重寻路 综合寻路--包括攻击考量的寻路算法 GamePlay 这是一个<文明> ...

  5. 【算法】A-star 算法摘录整合

    文章目录 1. 定义 1.1 定义解析 1.2 Dijkstra算法与最佳优先搜索 1.2.1 Dijkstra算法(距离起始点的信息) 1.2.2 最佳优先搜索(距离终点的信息) 1.2.3 以上两 ...

  6. Python:实现A-Star算法(附完整源码)

    Python:实现A-Star算法 import numpy as npclass Cell:def __init__(self):self.position = (0, 0)self.parent ...

  7. 利用Astar算法实现飞行轨迹的三维路径规划(基于Matlab代码实现)

    目录  1 概述     1.1研究背景  2 运行结果  3 Matlab代码实现  4 参考文献 1 概述 随着自动化技术的发展,现代航空技术水平有了前所未有的提高,促进了无人机在军事.民用领域的 ...

  8. 基于Astar算法的栅格地图最优路径搜索matlab仿真,可以修改任意数量栅格

    目录 1.算法描述 2.仿真效果预览 3.MATLAB核心程序 4.完整MATLAB 1.算法描述 Astar算法是一种图形搜索算法,常用于寻路.它是个以广度优先搜索为基础,集Dijkstra算法与最 ...

  9. 基于Astar算法的栅格地图目标最短路径搜索算法MATLAB仿真,带GUI界面

    目录 1.算法描述 2.仿真效果预览 3.MATLAB核心程序 4.完整MATLAB 1.算法描述 Astar算法是一种图形搜索算法,常用于寻路.它是个以广度优先搜索为基础,集Dijkstra算法与最 ...

  10. AStar 算法 ---在Unity当中实现

    介绍 AStar算法,是一种在静态路网中求最短路径的一种算法,是一种启发式的算法.其中,算法当中起点与终点的距离,与算法当中的预估距离越接近,则搜索速度越快. 其实,在AStar算法当中,他的搜索路径 ...

最新文章

  1. Matlab编程与数据类型 -- 多维数组
  2. ASP.Net4中实现自定义的请求验证(转贴)
  3. 区块链BaaS云服务(21)腾讯CCGP”跨链事务“
  4. 【Linux】一步一步学Linux——usernetctl命令(175)
  5. 【JSP笔记】第三章 JSP内置对象【上】
  6. 【计算机网络复习 数据链路层】3.5.2 ALOHA协议
  7. eclipse搭建maven开发环境
  8. spark中dataframe解析_Spark 结构流处理介绍和入门教程
  9. 【CentOS】 Nginx+jdk+tomcat 环境搭建
  10. chrome老版本_技术周刊 2019-08-06:Chrome 又隐藏了 www
  11. ztree 右键菜单功能
  12. 2019美赛b题:基于Weighted-K-means聚类模型的选址
  13. 基于单片机门电路测试
  14. python中的for什么意思_python中的for是什么
  15. Bandizip Archiver for mac(便捷解压缩软件)
  16. 选择勤哲Excel服务器做企业管理系统ERP的经验之谈
  17. 7-2 符号配对 (25 分)(C语言版)
  18. 软件分享系列之【AE 下载安装】并持续分享中...
  19. Git学习笔记及一些问题(廖雪峰版)
  20. AJAX应用的演示和源码

热门文章

  1. 基于android课设报告,基于android的简单用户注册系统课程设计报告.doc
  2. 天天生鲜(Django4.0版本) + 开发遇到的问题及解决
  3. leslie人口预测模型matlab代码,leslie模型人口预测程序,请求大家!
  4. 使用Tampermonkey进行JavaScript编程
  5. 阿里云加速器拉取tomcat
  6. 谷歌翻译突然用不了了
  7. Open3D:DBSCAN(C++)
  8. 【Python 代码】类似SADPTool工具,搜索海康设备
  9. UVC协议CT_ZOOM_RELATIVE_CONTROL选择子放大缩小停止的问题
  10. python 爬取西刺免费代理ip 并使用telnetlib.Telnet验证是否有效