【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使用的时候需要将这个偏移去掉,或者在创建的时候不要加偏移

其他

  • 完整代码再等等
相关推荐
wuhen_n9 分钟前
模板编译三阶段:parse-transform-generate
前端·javascript·vue.js
滕青山13 分钟前
正则表达式测试 在线工具核心JS实现
前端·javascript·vue.js
不可能的是14 分钟前
前端图片懒加载方案全解析
前端·javascript
wuhen_n15 分钟前
Fragment 与 Portal 的特殊处理
前端·javascript·vue.js
用户57573033462424 分钟前
🚀 JS事件机制大揭秘:从“橘子”报警到“列表”瘦身,前端老鸟都在偷笑的秘密!
javascript
用户57573033462429 分钟前
💎 JS 中的“隐形人”:Symbol 数据类型深度解密!从命名冲突到隐私保护
javascript
掘金安东尼1 小时前
Fun with TypeScript Generics:玩转 TS 泛型
前端·javascript·面试
掘金安东尼1 小时前
Next.js 企业级落地
前端·javascript·面试
掘金安东尼1 小时前
React 性能优化完全指南 2026
前端·javascript·面试
小霖家的混江龙1 小时前
从 0 到 1 实现一个 useState
前端·javascript·react.js