首页 > 解决方案 > 鼠标移动事件不同的坐标

问题描述

我有一个 3d 动画,我想用鼠标检测 colitions,我尝试用一​​个球跟随,这个球与鼠标的位置不同。

codepen 中的工作示例

此功能是此其他答案的复制粘贴,但对我不起作用。

// Follows the mouse event
function onMouseMove(event) {

    // Update the mouse variable
    event.preventDefault();
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

    // Make the sphere follow the mouse
    var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
    vector.unproject(camera);
    var dir = vector.sub(camera.position).normalize();
    var distance = - camera.position.z / dir.z;
    var pos = camera.position.clone().add(dir.multiplyScalar(distance));
    sphereInter.position.copy(pos);

    // Make the sphere follow the mouse
    sphereInter.position.set(event.clientX, event.clientY, 0);
}

如您所见,蓝色球与鼠标不同,我该如何解决?

标签: javascriptthree.js

解决方案


我建议您将mousemove事件侦听器添加到renderer.domElementdocument然后使用此代码来计算以下组件mouse

const rect = renderer.domElement.getBoundingClientRect();

mouse.x = ( ( event.clientX - rect.left ) / rect.width ) * 2 - 1;
mouse.y = - ( ( event.clientY - rect.top ) / rect.height ) * 2 + 1;

推荐阅读