前言
在游戏开发过程中,寻路可能是大多数游戏都必不可少的功能。2d游戏中最常用的就是A* 寻路了。在3d游戏中,对于一些简单的,没有高度地面A* 寻路同时也是可以使用的,但是对于一些地面比较复杂的游戏,寻路功能怎样实现比较好呢!
效果展示
1.RecastNavigation
相信了解过3d寻路的小伙伴都有听说过RecastNavigation。RecastNavigation是一款非常强大的寻路系统,被广泛的应用于各大游戏引擎中。如Unreal,Unity等。
NavMesh的生成基本原理:
- 体素化。从源几何体构造实心的高度场,用来表示不可行走的空间。
- 生成地区。将实心高度场的上表面中连续的区间合并为地区。
- 生成轮廓。检测地区的轮廓,并构造成简单多边形。
- 生成多边形网格。将轮廓分割成凸多边形。
- 生成高度细节。将多边形网格三角化,得到高度细节。
感兴趣的小伙伴们可以去了解一下,甚至可以去了解了解源码。源码也去看过,奈何自己C++实在太差
2.耳切法+A*
大概了解了导航寻路的原理,觉得整个寻路的关键可以分为两部分:网格画与寻路,所以决定自己尝试一下,现从最简单的没有高度的地图入手
大概步骤:
- 1.基于耳切法实现地图的网格化
- 2.基于A* 实现寻路
- 3.基于漏斗算法将三角形集合进行路径最优解
在最终的尝试下,基本的寻路功能是实现了,但是在路径的优化方面会存在一些问题,所以决定去寻找一些现成的js库来实现这个功能
3.NavMesh 导航
在github闲逛的时候发现了recast.js这个库,于是乎就开始花时间去了解了一下具体功能和API,同时还发现在Babylon.js这个3d游戏引擎中已经将其集成进去了,并且这个游戏引擎也是开源的,简直太完美了,
3.1 Cocos Creator3.x
花了点时间,成功将recast.js 移到了Cocos Creator3.x
- recast.js js库
- NavMesh.ts 功能实现
3.2 基础功能实现
1.初始化
import Recast from "./lib/recast.js"
...
public init(cb: Function = null):void{
new Recast().then((recast) => {
this._recast = recast;
this._navMesh = new this._recast.NavMesh();
this.setDefaultConfig();
this._tempVec=new this._recast.Vec3();
this._tempVec1=new this._recast.Vec3();
this._tempVec2=new this._recast.Vec3();
if (cb) cb();
});
}
2.添加静态物体
/**
* 添加静态的模型
*/
public addStaticModle(node: Node): void {
if(!node||!node.getComponent(MeshRenderer)) return;
let render: MeshRenderer = node.getComponent(MeshRenderer);
if (!render || !render.mesh) return;
let matrix: math.Mat4 = node.getWorldMatrix();
this.updateBaseDatas(render.mesh, matrix);
}
场景中一些固定不变的,比如地面,障碍物之类的可以通过这个结构进行添加,代码中对传入节点的网格信息进行处理,处理为recast所需要的格式,
3.生成导航网格
/**
* 构建导航网格
*/
public build(): void {
var rc = new this._recast.rcConfig();
rc.cs = this._config.cs;
rc.ch = this._config.ch;
....
this._navMesh.build(this._positions, this._positions.length / 3, this._indices, this._indices.length, rc);
}
导航网格构建成功,对返回的导航数据进行了一些额外的处理,将其处理为cocos支持的网格数据形式,将导航网格部分最终显示到界面上(红色部分)
/**
* 获取导航网格数据
*/
public getNavMeshDebugData(): NavMeshData {
...
return { positions: positions, normals: normals }
}
/*
*创建网格
*/
private createDebugMesh(positions: number[], normals: number[]): void {
this.node.destroyAllChildren();
let node = new Node();
let render = node.addComponent(MeshRenderer);
let mesh = utils.createMesh({
positions: positions,
primitiveMode: gfx.PrimitiveMode.TRIANGLE_LIST,
normals: normals,
});
render.mesh = mesh;
this.node.addChild(node);
}
4.寻路
/**
* 获取亮点之间的路径
* @param start
* @param end
* 返回所有的路近点
*/
public findPath(start: Vec3, end: Vec3): Vec3[] {
return positions;
}
总结
希望本次分享对大家有所帮助,demo中菜鸟对基础功能进行了分装,后续有时间还会逐渐完善补全,有兴趣的小伙伴可以去看看babylon.js 的源码以及使用,可以参照其进行功能的完善。