Three.js(6):vue中基于worker-loader使用web worker设置动态模型的移动路线

1 版本

vuecli:4.5.7

three.js:0.131.0


2 使用worker-loader

2.1 安装worker-loader

npm install worker-loader --save-dev

2.2 vue.config.js中进行配置

chainWebpack: config => {
    // 设置解析以worker.js 结尾的文件使用worker-loader 解析
   config.module.rule('worker-loader').test(/\.worker\.js$/).use('worker- 
   loader').loader('worker-loader').end();
   config.module.rule('js').exclude.add(/\.worker\.js$/);
}

3 创建Animate.worker.js用于不断更新模型位置信息

注意:必须以worker.js 结尾的文件才能使用worker-loader 解析

// animate.worker.js 文件
import * as THREE from "three/build/three.module.js";
onmessage = function (e) {
    console.info('animate.worker', e.data);
    const posArry = e.data; // e.data用于存储移动路线的数组
    const path = new THREE.LineCurve(posArry[0], posArry[1]);
    let curIndex = 0;
    setInterval(function () {
        let curPos, rotateY;
        curPos = calPosition(path,curIndex); //用于计算当前模型的位置
        rotateY = calHeading(path,curIndex); //用于计算当前模型的朝向
        curIndex = curIndex + 1;
        if (curIndex === 1000) {
            curIndex = 0;
        }
        postMessage({
            curPos,
            rotateY
        });
    }, 1000 / 30);
}

4 前端传递参数使用Animate.worker.js

// 前端vue文件
import animateWorker from "@/assets/js/three/hjq/worker/animate.worker.js";
// 封装方法:加载GLTF模型
loadGLTF(this_.mUrls.bird, (gltf) => {
    const mesh = gltf.scene;
    // path:路线数组
    const path = [
          [108.566, 40.688],
          [107.53, 40.551],
    ];
    // 封装方法:设置模型的初始位置
    setLocation(mesh, [path[0][0], 15, path[0][1]], [0, 0, 0], [0.1, 0.1, 0.1]);
    this_.mScene.add(mesh);
    // 解析gltf模型的动画
    this_.mBirdMixer = new THREE.AnimationMixer(mesh);
    this_.mBirdMixer.clipAction(gltf.animations[0]).play();
    if (window.Worker) {
          // animateWorker对应开头import的animate.worker.js
          const cowWorker = new animateWorker();
          cowWorker.postMessage(path);
          cowWorker.onmessage = function (e) {
                mesh.position.set(e.data.curPos.x, 15, e.data.curPos.y);
                mesh.rotation.set(0, e.data.rotateY + Math.PI * 1.1, 0);
          };
    }
});

5 实现效果

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碰碰qaq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值