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

说在前面

setAgentTarget

  • 使用recast navigation接口requestMoveTarget设置agent的目标位置
    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绘制寻路路径
    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,每帧重新绘制寻路路径
    public update(delta: number, scene: Scene) {
        this._crowd.update(delta)
        this.crowdHelper.update()
        this._updatePath(scene)
    }
    

结果

  • 鼠标右键设置agent起始位置
  • 鼠标左键设置agent目标位置
    在这里插入图片描述

问题

  • 最开始使用Teleport方法设置agent起点的时候,发现有些地方不太对,比如点击下图红色位置传送不过去
    在这里插入图片描述
    寻路也不对
    在这里插入图片描述
  • 后来发现是创建DebugDrawer的时候自己把它的位置做了下偏移
    const tmpDebugDrawer = new DebugDrawer();
        tmpDebugDrawer.drawNavMesh(mesh);
        tmpDebugDrawer.position.z += 10
    
  • 导致实际点击得到的位置也有一定的偏移,所以在传给recastnavigation使用的时候需要将这个偏移去掉,或者在创建的时候不要加偏移

其他

  • 完整代码再等等
  • 17
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值