javascript - 鼠标移动事件不同的坐标
问题描述
我有一个 3d 动画,我想用鼠标检测 colitions,我尝试用一个球跟随,这个球与鼠标的位置不同。
此功能是此其他答案的复制粘贴,但对我不起作用。
// 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;
推荐阅读
- r - 将 SAS 文件从具有特殊字符的目录导入 R
- sharepoint - 通过 webhook 发布到团队时,共享点中托管的图像不显示
- javascript - 是否可以将函数保存在数组中?
- sql - 如何在仅在其中一些列中的列上连接多个 SQL 表
- python - numpy 以另一个多维数组作为索引的设置值
- docker - Docker 镜像会改变吗?如何确保他们没有?
- python-3.x - 如何在不使用任何预定义函数的情况下对字符串列表进行排序?
- kubernetes - 端点已暴露,但尝试从同一命名空间中的另一个 pod 使用 netstat 无法访问它
- c# - Cosmos DB 预触发器如何从另一行获取值
- java - Spring Shedlock 不保证同步