threejs相机动画

发布时间 2023-05-05 12:12:25作者: web与webGL

threejs相机动画

import * as dat from "dat.gui";
import { GUI } from "../../utils/lil-gui.module.min.js";
import TWEEN from "@tweenjs/tween.js";



    const gui = new GUI();
    gui.domElement.style.right = "0px";
    gui.domElement.style.width = "300px";
    const cameratween = {
      camerachange: () => {
        const endPos = new THREE.Vector3(0, 160, 40);
        const endTarget = new THREE.Vector3(0, 160, 0);
        this.createCameraTween(endPos, endTarget);
      },
      camerareturnchange: () => {
        const endPos = new THREE.Vector3(0, 120, 300);
        let obj = this.scene.getObjectByName("mergeBones");
        const endTarget = obj;
        this.createCameraTween(endPos, endTarget);
      },
    };
    gui.add(cameratween, "camerachange").name("贴近");
    gui.add(cameratween, "camerareturnchange").name("返回");

  

    /**
     *相机动画函数,从A点飞行到B点,A点表示相机当前所处状态
     * @param {三维向量,表示动画结束相机位置} endPos
     * @param {三维向量,表示相机动画结束lookAt指向的目标观察点} endTarget
     */
    createCameraTween(endPos, endTarget) {
      const cameradata = this.camera;
      const orbitControlsdata = this.orbitControls;
      new TWEEN.Tween({
        // 不管相机此刻处于什么状态,直接读取当前的位置和目标观察点
        x: this.camera.position.x,
        y: this.camera.position.y,
        z: this.camera.position.z,
        tx: this.orbitControls.target.x,
        ty: this.orbitControls.target.y,
        tz: this.orbitControls.target.z,
      })
        .to(
          {
            // 动画结束相机位置坐标
            x: endPos.x,
            y: endPos.y,
            z: endPos.z,
            // 动画结束相机指向的目标观察点
            tx: endTarget.x,
            ty: endTarget.y,
            tz: endTarget.z,
          },
          2000
        )
        .delay(500)
        .easing(TWEEN.Easing.Quartic.InOut)
        .start() // define delay, easing
        .onUpdate(function (obj) {
          console.log(cameradata);
          // 动态改变相机位置
          cameradata.position.set(obj.x, obj.y, obj.z);
          // 动态计算相机视线
          // camera.lookAt(obj.tx, obj.ty, obj.tz);
          orbitControlsdata.target.set(obj.tx, obj.ty, obj.tz);
          orbitControlsdata.update(); //内部会执行.lookAt()
        });
      //.start();
    },

  最后