ThreeJS+MindAR鼠标点击放置3D物体存在偏移问题
问题分析与解决方案
你的问题出在错误地使用屏幕归一化鼠标坐标设置3D物体位置,而非射线检测得到的实际3D交点坐标。顶视图时,屏幕坐标和3D坐标的xy值巧合匹配,所以看起来正常;但角度视图下,3D空间的交点位置和屏幕鼠标的归一化坐标完全不对应,导致偏移。
修正后的代码
const mousePositionX = (e.clientX / window.innerWidth) * 2 - 1; const mousePositionY = -(e.clientY / window.innerHeight) * 2 + 1; const mouse = new THREE.Vector2(mousePositionX, mousePositionY); const raycaster = new THREE.Raycaster(); raycaster.setFromCamera(mouse, camera); const intersects = raycaster.intersectObjects(scene.children, true); if (intersects.length === 0) return; // 获取射线与物体的交点(世界空间坐标) const intersectPoint = intersects[0].point; topping = obj1.clone(); // 将世界坐标转换为anchor锚点的局部坐标 anchor.worldToLocal(intersectPoint); // 设置物体位置为转换后的局部坐标 topping.position.copy(intersectPoint); // 将物体添加到anchor组 anchor.add(topping);
关键说明
intersects[0].point是射线与目标物体相交的3D世界空间坐标,这才是你点击位置对应的真实3D位置。- 因为物体需要添加到
anchor锚点的局部空间,必须用anchor.worldToLocal()把世界坐标转换为锚点的局部坐标,否则位置会相对于整个场景而非锚点偏移。 - 原代码中直接用
mouse.x和mouse.y是屏幕归一化坐标(范围-1到1),和3D世界坐标的尺度、空间完全无关,只有顶视图这种特殊视角才会碰巧对应。
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

