Laya游戏开发中AI寻路解决方案

1.AI自动寻路:

机器人代码重构,按照目标点去执行逻辑,提前几帧判断直线,非直线的情况下,预设转弯角度,角度判断到达直线后开始执行到目标点的逻辑

2.U3D布点寻路

3.NevMesh.Js寻路插件

NevMesh.Js你可以在Laya引擎中直接使用的AI寻路 - 简书

Demo演示:www.layabox.com

Laya游戏开发中AI寻路解决方案_第1张图片

(1)U3D中使用NavMesh寻路系统,对障碍物就行烘焙,也就是对场景中的物体进行标记,然后烘焙路径,产生网格数据;为需要进行寻路的物体添加寻路组件NavMeshAgent,通过NavMeshAgent组件的属性或方法进行移动

Laya游戏开发中AI寻路解决方案_第2张图片

选中场景中所有障碍物和地面对象,勾选Navigation Static

Laya游戏开发中AI寻路解决方案_第3张图片

(2)cs文件拖入U3D项目中:

Laya游戏开发中AI寻路解决方案_第4张图片

然后 LayaAir3D中出现NavMesh导出, 然后会在工程目录生成一个ExportNavMesh文件夹,里面的文件就是导出的NavMesh模型obj文件

Laya游戏开发中AI寻路解决方案_第5张图片

Laya游戏开发中AI寻路解决方案_第6张图片

(3) 这时候需要将导出的obj文件利用转换工具转换成json格式的文件,让Laya读取

Laya游戏开发中AI寻路解决方案_第7张图片

运行转化代码:

python convert_obj_three.py -i testScene.obj -o out.json

Laya游戏开发中AI寻路解决方案_第8张图片

(4)项目使用的脚本,将NevMesh.js放到项目bin/libs文件夹中,将NevMesh.d.ts放到项目libs文件夹中,在bin/index.js中增加loadLib("libs/NevMesh.js"),注意需在loadLib("js/bundle.js");前面

Laya游戏开发中AI寻路解决方案_第9张图片

loadLib("libs/NevMesh.js")
//-----libs-end-------
loadLib("js/bundle.js");

(5)加载导出的.json文件

this.navUrl="meshes/outfile.json";

Laya.loader.load(this.navUrl,Laya.Handler.create(this,this.onNavLoaded),null,"json");

onNavLoaded(){
    var json=Laya.loader.getRes(this.navUrl);
    let zoneNodes =  NevMesh.buildNodesByJson(json);
    NevMesh.setZoneData('game',zoneNodes);
    this.playerNavMeshGroup = NevMesh.getGroup('game', this.player.transform.position);
}

(6)初始化寻路对象:

this.player=sceneLoad.getChildByName("player");
this.physicsSimulation=sceneLoad.physicsSimulation;  //物理模拟器


this.agent=null;
this.agent=this.player.addComponent(NavMeshAgent);
this.agent.speed=10;

(7)鼠标点击目标位置点,射线检测,开始寻路:

//创建射线
this.ray=new Laya.Ray(new Laya.Vector3(),new Laya.Vector3());
//射线检测结果
this.hitResult=new Laya.HitResult();
    this.camera.viewportPointToRay(new Laya.Vector2(Laya.stage.mouseX,Laya.stage.mouseY),this.ray);
        if(this.physicsSimulation.rayCast(this.ray,this.hitResult)){
            console.log("000");
            this.targetPos=this.hitResult.point;
            let calculatedPath = NevMesh.findPath(this.player.transform.position,this.targetPos, 'game',this.playerNavMeshGroup);


            if (calculatedPath && calculatedPath.length){
                var debugPath=(calculatedPath);
                console.log("start",this.player.transform.position.x,this.player.transform.position.y,this.player.transform.position.z);
                var p=[];
                for (var i=0;i < debugPath.length;i++){
                    console.log(debugPath[i].x,debugPath[i].y,debugPath[i].z);
                    p.push(new Laya.Vector3(debugPath[i].x,debugPath[i].y+.1,debugPath[i].z));
                }
               
                this.agent.path=[this.player.transform.position].concat(p);
                this.agent.enabled=true;
                console.log("end",this.targetPos.x,this.targetPos.y,this.targetPos.z);
            }
            else{
                this.agent.enabled=false;
            }
        }

你可能感兴趣的:(人工智能,javascript,游戏程序)