本文介绍的是使用gltf格式的模型,其他模型格式请自行修改本文第二块代码
1.自定义一个路径曲线

Let curve = new THREE.CatmullRomCurve3([
          new THREE.Vector3(0, 0, 0),
          new THREE.Vector3(-10, 0, 0),
          new THREE.Vector3(-50, 0, 0),
          new THREE.Vector3(-80, 0, 0),
          new THREE.Vector3(-100, 0, 0),
          new THREE.Vector3(-120, 0, 0),
          new THREE.Vector3(-120, 0, -30),
          new THREE.Vector3(-120, 0, -60)
       ]);
 // 样条曲线均匀分割100分,返回51个顶点坐标
        var points = curve.getPoints(100);
         var geometry = new THREE.Geometry();
            geometry.vertices = points
      // 绘制轨迹线
     let material = new THREE.LineBasicMaterial({
          color: 0x4488ff
        });
        let line = new THREE.Line(geometry, material);

        this.scene.add(line);

2.加载Gtlf或者glb文件实现动画效果(需注意,必须模型本身自己的动画,不然转向会有问题)

loader.load(gltfPath, function (gltf) {
           carMesh = gltf.scene;
            gltf.scene.scale.set(5,5,5);
            gltf.scene.position.set(0,50,0)
            carMesh.rotation.y = Math.PI;
            self.scene.add(gltf.scene);
            group.add(gltf.scene);
//实现模型动画
            mixer = new THREE.AnimationMixer(carMesh);
           let action = mixer.clipAction(gltf.animations[10]);
            action.play();
              self.render();

3.animate或者 render回调里 根据以上核心知识点来控制模型旋转和移动。

 if(mixer){
        //模型移动
        mixer.update(clock.getDelta());
        }
         TWEEN.update();
        //添加控制开关,GO是去,BACK是回来,这样可以来回移动
        if (this.carDirection === 'GO') {
          if (progress > 1.0) {
            this.carDirection = 'BACK'
          } else {
            progress += 0.0009;
          }
        } else {
          if (progress < 0) {
            this.carDirection = 'GO'
          } else {
          progress -= 0.0009;
          }
        }
        if (curve && carMesh) {
          let point = curve.getPoint(progress);
          //模型的偏移量
          let offsetAngle = Math.PI;
          //创建一个4维矩阵
          let mtx = new THREE.Matrix4();
          mtx.lookAt(carMesh.position.clone(), point, carMesh.up);
          mtx.multiply(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(0, offsetAngle, 0)));
          //计算出需要进行旋转的四元数值
          let toRot = new THREE.Quaternion().setFromRotationMatrix(mtx);
          //根据以上值调整角度
          carMesh.quaternion.slerp(toRot, 0.2);
          carMesh.position.set(point.x, point.y, point.z);
        }

创作不易,转载请说明明处

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐