監聽事件
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);
}
};