【问题标题】:mouse movent event not same coords鼠标移动事件不同的坐标
【发布时间】:2021-08-12 15:53:00
【问题描述】:

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

Working example in codepen

此功能是this other answer 的复制粘贴,但对我不起作用。

// 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);
}

如你所见,蓝球和鼠标不在同一个地方,我该如何解决?

【问题讨论】:

    标签: javascript three.js


    【解决方案1】:

    我建议您将mousemove 事件监听器添加到renderer.domElement 而不是document,然后使用此代码计算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;
    

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 2016-12-09
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多