通过鼠标事件获取鼠标位置在3d中的坐标mouse/Raycaster

 

 

监听事件

    ThreeDom.current.addEventListener('mousemove', mousemoveFunc, false);

监听方法

 const mousemoveFunc = (event) => {
    event.preventDefault();
    // 计算鼠标在屏幕上的位置
    const mouse = new THREE.Vector2();
    // 计算鼠标在屏幕上的位置
    const mouse = new THREE.Vector2();
    const getBoundingClientRect = ThreeDom.current.getBoundingClientRect();
    mouse.x = ((event.clientX - getBoundingClientRect.left) / ThreeDom.current.offsetWidth) * 2 - 1; // 标准设备横坐标
    mouse.y = -((event.clientY - getBoundingClientRect.top) / ThreeDom.current.offsetHeight) * 2 + 1; // 标准设备纵坐标

     //全屏时使用
    // mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    // mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;


    // 将屏幕坐标转换为3D坐标
    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(mouse, Three.camera);

    // 获取鼠标位置对应的3D坐标
    const intersects = raycaster.intersectObjects(Three.scene.children, true);
    console.log(intersects);

    if (intersects.length > 0) {
      const position = intersects[0].point;
      console.log('3D坐标: ', position);
    }
  };

 

posted @ 2024-10-29 18:40  SimoonJia  阅读(8)  评论(0编辑  收藏  举报