gpt4 book ai didi

javascript - 鼠标移动事件不相同的坐标

转载 作者:行者123 更新时间:2023-12-04 07:37:12 24 4
gpt4 key购买 nike

我有一个 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);
}
如您所见,蓝球与鼠标不在同一个位置,我该如何解决?

最佳答案

我建议你添加 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;

关于javascript - 鼠标移动事件不相同的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67670426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com