0
点赞
收藏
分享

微信扫一扫

Threejs用切线实现模型沿着轨道行驶

zhyuzh3d 03-09 13:15 阅读 1

        这次讲一个经常遇到的使用场景,让模型沿着轨迹运动,这个场景需要解决两个问题,第一是让模型沿着轨迹运动,第二是在沿着轨迹运动的同时,要保持模型的头部也时刻保持前方,而不是单纯的只是更新模型位置。

        还是先创建一个场景,添加相机,灯光,渲染器等,然后需要创建一个轨迹,这里用CatmullRomCurve3创建一个3维曲线,这个的好处是等会可以将此曲线拆解成多个同等份的点,因为我们需要不断更新模型在此曲线的位置,实际上就是不停的切换此曲线上连接的多个点,来实现位置的不断更新。

        首先根据四个点创建曲线,并将曲线分解为多个点,再用这些点绘制成一条曲线并加入到场景中,方便后面观察模型的运动轨迹。

 this.cameraCurve = new THREE.CatmullRomCurve3(
          [
            new THREE.Vector3(-300, 40, 200),
            new THREE.Vector3(300, 40, 200),
            new THREE.Vector3(300, 40, -200),
            new THREE.Vector3(-300, 40, -200),
          ],
          true
      );
      //参考路径上取1000个点,每个点上添加蓝色小球
      const pathPoints = this.cameraCurve.getPoints(this.pathIndex);
      //绘制一条路径参考线与上面的线重合,方便查看小车的行动轨迹
      const geometry = new THREE.BufferGeometry().setFromPoints(pathPoints);
      const material = new THREE.LineBasicMaterial({ color: '#000000', linewidth: 1, });//设置线条的颜色和宽度
      const curveObject = new THREE.Line(geometry, material);
      scene.add(curveObject);

此时场景中就出现一条曲线,作为模型运动的轨迹,

Threejs用切线实现模型沿着轨道行驶_ThreeJs

接着,需要在场景中添加一个模型,我这添加一个agv车,更方便观察车的车头方向,因为是外部模型需要加载GLTFLoader,缩放到适合的大小,并将车的位置放在曲线的第一个点位置,防止在运动前突然闪现到开始运动的点开始运动。

 //在场景中加载一个agv小车,并将agv小车放在曲线的第一个点上
      const loader = new GLTFLoader()
      loader.load("/static/model/agv.gltf", (gltf) => {
        this.agv = gltf.scene;
        this.agv.position.set(pathPoints[0].x, pathPoints[0].y, pathPoints[0].z)   // 模型位置
        this.agv.scale.set(0.1,0.1,0.1)
        scene.add(this.agv)   // 加入场景
      })

Threejs用切线实现模型沿着轨道行驶_ThreeJs_02

曲线和车都加好了,需要开始设置动画了,也是最关键的部分,运动的部分比较简单,因为获取到了曲线的多个连续点,只需要不断地更新车的位置到每个点就好了,保持车头方向需要先获取车所在点向量的切线,位置向量和切线向量相加即为所需朝向的点向量。

 if (this.agv) {// 判断agv加载完成后,开始不断更新agv的位置
        const sphereCurveIndex = this.pathIndex / 1000; // //取相参考径上当前点的坐标,取值0~1
        const positionVec = this.cameraCurve.getPointAt(sphereCurveIndex);//获取曲线上位置的点,传值为0-1的小数表示整个线段的位置
        this.agv.position.set( positionVec.x, positionVec.y, positionVec.z);//设置新的agv位置
        const tangent = this.cameraCurve.getTangentAt(sphereCurveIndex); // 返回一个点t在曲线上位置向量的法线向量(getTangentAt是返回曲线上某个点的切线)
        const lookAtVec = tangent.add(positionVec);// 位置向量和切线向量相加即为所需朝向的点向量
        this.agv.lookAt(lookAtVec);//设置agv的模型朝向为切线的方向
      }

完整的代码如下:

<template>
  <div>
    <div id="container"></div>
  </div>
</template>

<script>
import * as THREE from 'three'
import {OrbitControls} from "three/addons/controls/OrbitControls";
import {GLTFLoader} from "three/addons/loaders/GLTFLoader";

let scene;
export default {
  name: "agv-single",
  data() {
    return{
      camera:null,
      cameraCurve:null,
      renderer:null,
      container:null,
      controls:null,
      pathIndex:1000,//小车的运动轨迹点索引
      agv:null
    }
  },
  methods:{
    initScene(){
      scene = new THREE.Scene();
    },
    initCamera(){
      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
      this.camera.position.set(500,500,500);
    },
    initLight(){
      //添加两个平行光
      const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);
      directionalLight1.position.set(-300,-300,600)
      scene.add(directionalLight1);
      const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);
      directionalLight2.position.set(600,200,600)
      scene.add(directionalLight2);
    },
    initRound(){
      //通过CatmullRomCurve3连接4个点绘制一条曲线,且闭合
      this.cameraCurve = new THREE.CatmullRomCurve3(
          [
            new THREE.Vector3(-300, 40, 200),
            new THREE.Vector3(300, 40, 200),
            new THREE.Vector3(300, 40, -200),
            new THREE.Vector3(-300, 40, -200),
          ],
          true
      );
      //参考路径上取1000个点,每个点上添加蓝色小球
      const pathPoints = this.cameraCurve.getPoints(this.pathIndex);
      //绘制一条路径参考线与上面的线重合,方便查看小车的行动轨迹
      const geometry = new THREE.BufferGeometry().setFromPoints(pathPoints);
      const material = new THREE.LineBasicMaterial({ color: '#000000', linewidth: 1, });//设置线条的颜色和宽度
      const curveObject = new THREE.Line(geometry, material);
      scene.add(curveObject);

      //在场景中加载一个agv小车,并将agv小车放在曲线的第一个点上
      const loader = new GLTFLoader()
      loader.load("/static/model/agv.gltf", (gltf) => {
        this.agv = gltf.scene;
        this.agv.position.set(pathPoints[0].x, pathPoints[0].y, pathPoints[0].z)   // 模型位置
        this.agv.scale.set(0.1,0.1,0.1)
        scene.add(this.agv)   // 加入场景
      })
    },
    initRenderer(){
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.container = document.getElementById("container")
      this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
      this.renderer.setClearColor('#AAAAAA', 1.0);
      this.container.appendChild(this.renderer.domElement);
    },
    initControl(){
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true;
      this.controls.maxPolarAngle = Math.PI / 2.2;      // // 最大角度
    },
    initAnimate() {
      //参考路径的索引在1001~0中往复减少以实现小车循环行驶
      if (this.pathIndex === 0) {
        this.pathIndex = 1001;
      }
      this.pathIndex -= 1;
      if (this.agv) {// 判断agv加载完成后,开始不断更新agv的位置
        const sphereCurveIndex = this.pathIndex / 1000; // //取相参考径上当前点的坐标,取值0~1
        const positionVec = this.cameraCurve.getPointAt(sphereCurveIndex);//获取曲线上位置的点,传值为0-1的小数表示整个线段的位置
        this.agv.position.set( positionVec.x, positionVec.y, positionVec.z);//设置新的agv位置
        const tangent = this.cameraCurve.getTangentAt(sphereCurveIndex); // 返回一个点t在曲线上位置向量的法线向量(getTangentAt是返回曲线上某个点的切线)
        const lookAtVec = tangent.add(positionVec);// 位置向量和切线向量相加即为所需朝向的点向量
        this.agv.lookAt(lookAtVec);//设置agv的模型朝向为切线的方向
      }
      requestAnimationFrame(this.initAnimate);
      this.renderer.render(scene, this.camera);
    },
    initPage(){
      this.initScene();
      this.initCamera();
      this.initLight();
      this.initRenderer();
      this.initControl();
      this.initRound();
      this.initAnimate();
    }
  },
  mounted() {
    this.initPage()
  }
}
</script>

<style scoped>
#container{
  position: absolute;
  width:100%;
  height:100%;
  overflow: hidden;
}
</style>

最终效果如下,这里没办法放视频,我就放个截图了

Threejs用切线实现模型沿着轨道行驶_ThreeJs_03

举报

相关推荐

0 条评论