vue+threejs写控件:双摄相机,显示固定视角

584 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第28天,点击查看活动详情


前言

本文主要使用vue+three.js写双摄相机控件,小窗口固定相机视角显示场景,演示gif如下图所示:

20221027_111024.gif

正文

html和css

创建一个id容器,用于存放渲染器节点。创建一个inset_box,用于存放小窗口固定相机视角。

<template>
  <div class="item">
    <div id="THREE69"></div>
    <div class="inset_box"></div>
  </div>
</template>

<style lang="less" scoped>
.inset_box {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 200px;
  height: 200px;
  overflow: hidden;
  border-radius: 3px;
  border: 5px solid rgba(255, 255, 255, 0.8);
}
</style>

引入three.js和相应的模块

OrbitControl轨道控制器,用于鼠标控制场景缩放平移旋转。GLTFLoader模型加载器,用于加载gltf模型

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

data()中定义的变量

camera相机,camera2小窗口固定相机,scene场景,renderer渲染器,gltfLoader模型加载器,controls轨道控制器,manager模型加载进度管理,insetWidth小窗口宽度,insetHeight小窗口高度

  data() {
    return {
      camera: null,
      camera2: null,
      scene: null,
      renderer: null,
      gltfLoader: null,
      controls: null,
      manager: null,
      clock: null,
      mixer: null, // 混合动画器
      Robot: null, // 机器人模型
      curve: null, // 运动轨迹
      insetWidth: 200,
      insetHeight: 200,
    };
  },

mounted()中调用的方法

initScene创建场景,initCamera创建相机,initLight创建灯光,initRenderer创建渲染器,initControls创建轨道控制器,initGround创建地面,initCurve使用Catmull-Rom算法从一系列的点创建一条平滑的三维曲线,initModel加载模型,this.manager.onLoad模型加载完成方法

  mounted() {
    this.manager = new THREE.LoadingManager();
    this.gltfLoader = new GLTFLoader(this.manager);
    this.clock = new THREE.Clock();
    this.initScene();
    this.initCamera();
    this.initLight();
    this.initRenderer();
    this.initControls();
    this.initGround();
    this.initCurve();
    this.initModel();
    this.manager.onLoad = () => {
      this.animate();
      console.log("Loading complete!");
    };
  },

创建场景

    initScene() {
      this.scene = new THREE.Scene();
    },

创建两个相机

camera是正常场景的相机,camera2是用于小窗口固定视角的相机,设置其固定位置为(0, 2, 4),视角一直转向(0, 0, 0)

    initCamera() {
      this.camera = new THREE.PerspectiveCamera(
        50,
        (window.innerWidth - 201) / window.innerHeight,
        1,
        1000
      ); // 透视相机
      this.camera.position.set(2, 2, 4); // 设置相机位置

      // 创建透视相机
      this.camera2 = new THREE.PerspectiveCamera(50, 1, 1, 1000);
      this.camera2.position.set(0, 2, 4); // 设置相机位置
      this.camera2.lookAt(0, 0, 0);
    },

创建灯光

创建一个平行光和一个环境光

    initLight() {
      const light = new THREE.DirectionalLight(0xffffff); // 平行光
      light.position.set(0.5, 1.0, 0.5).normalize(); // 设置平行光的方向,从(0.5, 1.0, 0.5)->target一般(0, 0, 0)
      this.scene.add(light); // 将灯光添加到场景中

      const ambLight = new THREE.AmbientLight(0xf0f0f0, 0.1); // 环境光
      this.scene.add(ambLight);
    },

创建渲染器

创建渲染器并将渲染器dom节点插入到html中

    initRenderer() {
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.outputEncoding = THREE.sRGBEncoding;
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.renderer.setSize(window.innerWidth - 201, window.innerHeight);
      document.getElementById("THREE69").appendChild(this.renderer.domElement);
    },

创建轨道控制器

轨道控制器控制的是camera相机

    initControls() {
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    },

创建地面

创建一块灰色的地面

    initGround() {
      const ground = new THREE.Mesh(
        new THREE.BoxGeometry(4, 0.0015, 4),
        new THREE.MeshPhongMaterial({
          color: 0x999999,
          depthWrite: false,
          transparent: true,
          opacity: 1,
        })
      );
      ground.receiveShadow = true;
      ground.position.y = -0.0015;
      this.scene.add(ground);
    },

创建运行轨迹

使用Catmull-Rom算法从一系列的点创建一条平滑的三维曲线

    initCurve() {
      this.curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3(1, 0, -1),
        new THREE.Vector3(1, 0, 1),
        new THREE.Vector3(-1, 0, 1),
        new THREE.Vector3(-1, 0, -1),
      ]);
      this.curve.curveType = "centripetal"; // 曲线的类型
      this.curve.closed = true; // 曲线是否闭合
      const points = this.curve.getPoints(50); // 获取点列表,50为要将曲线划分为的分段数
      const line = new THREE.LineLoop(
        new THREE.BufferGeometry().setFromPoints(points),
        new THREE.LineBasicMaterial({ color: 0x0000ff })
      ); // 一条头尾相接的连续的线(参数说明:顶点列表,材质)
      this.scene.add(line); // 将曲线添加到场景中
    },

加载模型并制定动画

    initModel() {
      this.gltfLoader.load(
        "./models/models/gltf/RobotExpressive/RobotExpressive.glb",
        (gltf) => {
          gltf.scene.scale.set(0.1, 0.1, 0.1);
          this.Robot = gltf.scene;
          this.scene.add(gltf.scene);

          const animations = gltf.animations;
          this.mixer = new THREE.AnimationMixer(this.Robot); // 动画混合器
          let actions = {};
          for (let i = 0; i < animations.length; i++) {
            const clip = animations[i];
            const action = this.mixer.clipAction(clip);
            actions[clip.name] = action;
          }
          // 制定动画
          actions["Walking"]
            .reset() // 重置动作
            .play(); // 让混合器激活动作
        }
      );
    },

动画函数并渲染场景(重点)

先执行动画,让小机器人动起来,再调整小机器人的走路位置和朝向,然后是本文实现双摄相机的关键,使用.setClearColor()方法设置渲染的场景的颜色及其透明度,使用.setViewport()方法设置视口大小,设置完之后渲染正常视角this.renderer.render(this.scene, this.camera);使用的是camera相机。

再使用.setClearColor()方法设置渲染的场景的颜色及其透明度,并且使用.clearDepth()方法清除深度缓存,.setScissorTest(true)启用剪裁检测,只有在所定义的裁剪区域内的像素才会受之后的渲染器影响,使用.setScissor()方法设置裁剪区域,使用.setViewport()方法设置视口大小,设置完之后渲染小窗口固定视角,使用的是camera2相机。最后.setScissorTest(false)禁用剪裁检测。

    animate() {
      requestAnimationFrame(this.animate);

      // 执行动画
      const dt = this.clock.getDelta();
      if (this.mixer) {
        this.mixer.update(dt);
      }

      // 调整走路位置和朝向
      const loopTime = 25 * 1000; // 定义循环一圈所需的时间
      let time = Date.now();
      let t = (time % loopTime) / loopTime; // 计算当前时间进度百分比
      const position = this.curve.getPointAt(t); // 参数t表示当前点在线条上的位置百分比,该方法根据传入的百分比返回在曲线上的位置
      this.Robot.position.copy(position); // 更新机器人的位置
      const tangent = this.curve.getTangentAt(t); // 该方法根据传入的百分比返回在曲线上的位置的切线
      const lookAtVec = tangent.add(this.Robot.position); // 位置向量和切线向量相加即为所需朝向的点向量
      this.Robot.lookAt(lookAtVec); // 更新机器人朝向

      // 双摄相机
      this.renderer.setClearColor(0x000000, 1);
      this.renderer.setViewport(
        0,
        0,
        window.innerWidth - 201,
        window.innerHeight
      );
      this.renderer.render(this.scene, this.camera);

      this.renderer.setClearColor(0x444444, 1);
      this.renderer.clearDepth();
      this.renderer.setScissorTest(true);
      this.renderer.setScissor(
        window.innerWidth - 416,
        window.innerHeight - 215,
        this.insetWidth,
        this.insetHeight
      );
      this.renderer.setViewport(
        window.innerWidth - 416,
        window.innerHeight - 215,
        this.insetWidth,
        this.insetHeight
      );
      this.renderer.render(this.scene, this.camera2);
      this.renderer.setScissorTest(false);
    },

结尾

以上即是所有的代码和代码说明。