【THREE.JS笔记】选中模型,导入视频以及通过距离调整音量

定义变量

    let textLeft, videoLeft, ifVideoLeft = false;

导入视频

    videoLeft = document.createElement('video');
    videoLeft.preload = 'auto';
    videoLeft.controls = 'controls';
    videoLeft.volume = 1;
    videoLeft.style.objectFit = 'fill';
    let videoSource = document.createElement('source');
    videoSource.type = 'video/mp4';
    videoSource.src = './video/huacaozhi1.mp4';
    videoLeft.appendChild(videoSource);
    let geometryLeft1 = new THREE.BoxGeometry(4, 2, 0);
    let materialLeft1 = new THREE.MeshPhongMaterial({
      map: new THREE.VideoTexture(videoLeft)
    });
    textLeft = new THREE.Mesh(geometryLeft1, materialLeft1);
    textLeft.name = 'videoLeft1';
    scene.add(textLeft)

通过距离改变音量大小,假如距离过远自动暂停

    let cameraP = camera.position;
    let textLeftP = textLeft.position;
    let distance1 = cameraP.distanceTo(textLeftP);
    //textLeft2视频
    if (distance1 <= 30) {
      videoLeft.volume = 1 - distance1 / 30;
    } else {
      ifVideoLeft = false;
      videoLeft.pause();
    }

选中模型,点击播放视频

document.addEventListener('click', initRay, false);

function initRay(event) {
    // 获取画布
    let mainCanvas2 = document.querySelector("#container");
    // 将屏幕坐标转为标准设备坐标(支持画布非全屏的情况)
    let x2 = ((event.clientX - mainCanvas2.getBoundingClientRect().left) / mainCanvas2.offsetWidth) * 2 - 1;   // 设备横坐标
    let y2 = -((event.clientY - mainCanvas2.getBoundingClientRect().top) / mainCanvas2.offsetHeight) * 2 + 1;  // 设备纵坐标
    let standardVector2 = new THREE.Vector3(x2, y2, 1);// 设备坐标
    // 标准设备坐标转为世界坐标
    let worldVector2 = standardVector2.unproject(camera);
    // 射线投射方向单位向量(worldVector坐标减相机位置坐标)
    let ray2 = worldVector2.sub(camera.position).normalize();
    // 创建射线投射器对象
    let rayCaster2 = new THREE.Raycaster(camera.position, ray2);
    // 返回射线选中的对象数组(第二个参数默认值是false,意为是否遍历图形内部的所有子图形)
    let intersects2 = rayCaster2.intersectObjects(scene.children, true);
    if (intersects2.length > 0) {
      // 射线拾取的首个对象
      let currObj2 = intersects2[0];
      // console.log(currObj2.object)
      // console.log(currObj2.object.name);
      if (currObj2.object.name === 'videoLeft1') {
        if (ifVideoLeft === false) {
          ifVideoLeft = true;
          videoLeft.play();
        } else {
          videoLeft.pause();
        }
      }
    }
  }

你可能感兴趣的:(【THREE.JS笔记】选中模型,导入视频以及通过距离调整音量)