如果json文件有三四百kb以上,那么构建寻路的时候会非常卡,甚至阻塞模型加载,这时候可以使用worker来构建新的线程避免阻塞页面的模型
使用worker处理阻塞问题
navWorker.js: 这个文件放在src中在运行的时候会报错找不到,所以worker代码必须放在bin目录下,但是在bin目录下又无法读取Laya,window,NevMesh等全局变量,所以,必须在这里引入NevMesh.js来执行计算
(function (){
if ('function' === typeof importScripts) {
importScripts("../NevMesh.js");
self.addEventListener('message', function (e) {
let floorNum = e.data[1];
let navUrl = e.data[2];
console.log('new worker msg:', floorNum)
var xmlreq = new XMLHttpRequest();
xmlreq.responseType = "json";
xmlreq.onload = function (e) {
var data = e.currentTarget.response;
let zoneNodes = NevMesh.buildNodesByJson(data);
self.postMessage([floorNum, zoneNodes]);
}
xmlreq.open("get",navUrl);
xmlreq.send();
}, false);
}
}())
主线程代码
initNavMesh() {
let self = this;
let { buildingName, currFloor, isStack, buildingInfo } = this.sceneInfo;
if (isStack) {
for (var key in buildingInfo) {// 多层路线构建
if (NevMesh.zoneNodes[key] || this.workList.includes(key)) {
} else {
this.workList.push(key);
nWork(key);
}
}
if (this.workList.length === 0) this.initComplete();
} else {
if (NevMesh.zoneNodes[currFloor]) {
this.initComplete();
} else if (this.workList.includes(currFloor)) {
} else {
this.workList.push(currFloor);
nWork(currFloor);
}
}
function nWork(key) {// 构建需要提示
var worker = new Laya.Browser.window.Worker("js/navWorker.js");
worker.onmessage = function (oEvent): void {
let floorNum = oEvent.data[0];
let zoneNodes = oEvent.data[1];
NevMesh.setZoneData(floorNum, zoneNodes);
let id = self.workList.findIndex((val) => {
return val === floorNum;
});
self.workList.splice(id, 1);
if (self.workList.length === 0) {
self.initComplete();
if (isStack) {
// self.findPathByPos(false);
// self.findDemo(false);
} else {
// self.findPathByPos(true, floorNum);
}
}
console.log(`${buildingName}/${floorNum} 导航数据构建完毕`);
};
worker.postMessage(["start", key, `../meshes/${buildingName}/${key}.json`]);// meshes文件夹要放在bin目录下,如果放在src里会找不到
}
}