【recast-navigation-js】使用three.js辅助绘制Agent寻路路径

目录

说在前面

setAgentTarget

  • 使用recast navigation接口requestMoveTarget设置agent的目标位置

    typescript 复制代码
    public setAgentTarget(pos: Vector3) {
    
        const { point: target } = this._meshQuery.findClosestPoint(pos);
        this._agent.requestMoveTarget(target);
    
        this._agentTarget = new Vector3().copy(target as Vector3)
    }

绘制寻路路径

  • 使用three.js中的Line绘制寻路路径

    typescript 复制代码
    private _updatePath(scene: Scene) {
        if (!this._agentTarget) {
            return
        }
        const path = []//[this._agent.position(), ...this._agent.corners()];
        path.push(new Vector3().set(this._agent.position().x, this._agent.position().y, this._agent.position().z))
        this._agent.corners().forEach((v) => {
            path.push(new Vector3().set(v.x, v.y, v.z))
        })
    
        if (path.length <= 1) {
            return
        }
    
        const spline = new CatmullRomCurve3(path);
    
        const samples = spline.getPoints(path.length * 12);
        const geometrySpline = new BufferGeometry().setFromPoints(samples);
    
        const line = new Line(geometrySpline, new LineDashedMaterial({ color: 0x66ccff, dashSize: 1, gapSize: 0.5 }));
        line.computeLineDistances();
    
        if (this.crowdPathLine) {
            scene.remove(this.crowdPathLine)
        }
        this.crowdPathLine = line
        scene.add(line)
    }
  • CatmullRomCurve3
    给定输入点,创建相对平滑的曲线(实际上可以不用这个,使用实际的寻路关键点更能反映寻路结果)

  • LineDashedMaterial
    虚线材质

  • update,每帧重新绘制寻路路径

    typescript 复制代码
    public update(delta: number, scene: Scene) {
        this._crowd.update(delta)
        this.crowdHelper.update()
        this._updatePath(scene)
    }

结果

  • 鼠标右键设置agent起始位置
  • 鼠标左键设置agent目标位置

问题

  • 最开始使用Teleport方法设置agent起点的时候,发现有些地方不太对,比如点击下图红色位置传送不过去

    寻路也不对

  • 后来发现是创建DebugDrawer的时候自己把它的位置做了下偏移

    typescript 复制代码
    const tmpDebugDrawer = new DebugDrawer();
        tmpDebugDrawer.drawNavMesh(mesh);
        tmpDebugDrawer.position.z += 10
  • 导致实际点击得到的位置也有一定的偏移,所以在传给recastnavigation使用的时候需要将这个偏移去掉,或者在创建的时候不要加偏移

其他

  • 完整代码再等等
相关推荐
Best_Liu~1 分钟前
el-table实现固定列,及解决固定列导致部分滚动条无法拖动的问题
前端·javascript·vue.js
苏十八2 小时前
前端进阶:Vue.js
前端·javascript·vue.js·前端框架·npm·node.js·ecmascript
爱上电路设计3 小时前
有趣的算法
开发语言·c++·算法
studyForMokey3 小时前
kotlin 函数类型接口lambda写法
android·开发语言·kotlin
乐容3 小时前
vue3使用pinia中的actions,需要调用接口的话
前端·javascript·vue.js
2401_858120263 小时前
探索sklearn文本向量化:从词袋到深度学习的转变
开发语言·python·机器学习
似水明俊德4 小时前
ASP.NET Core Blazor 5:Blazor表单和数据
java·前端·javascript·html·asp.net
与墨学长4 小时前
Rust破界:前端革新与Vite重构的深度透视(中)
开发语言·前端·rust·前端框架·wasm
虫小宝5 小时前
Java中的软件架构重构与升级策略
java·开发语言·重构
CTGU_daffodil5 小时前
matlab 绘制高等数学中的二维函数示例
开发语言·matlab