Rob*_*ans 57 point projection mouse-coordinates three.js
我一直在寻找一个与我的用例相匹配的例子,却找不到一个.我正在尝试将屏幕鼠标坐标转换为考虑到相机的3D世界坐标.
解决方案我发现所有人都做射线交叉以实现对象拾取.
我想要做的是将Three.js对象的中心定位在鼠标当前"结束"的坐标上.
我的相机位于x:0,y:0,z:500(虽然它会在模拟过程中移动)并且我的所有物体都在z = 0时具有不同的x和y值,所以我需要知道基于X,Y的世界假设az = 0表示跟随鼠标位置的对象.
这个问题看起来像一个类似的问题,但没有解决方案:在THREE.js中获取鼠标相对于3D空间的坐标
给定屏幕上的鼠标位置,其范围为"左上角= 0,0 |右下角= window.innerWidth,window.innerHeight",任何人都可以提供将Three.js对象移动到鼠标坐标的解决方案沿z = 0?
Wes*_*ley 112
您不需要在场景中有任何对象来执行此操作.
你已经知道相机的位置了.
使用vector.unproject( camera )你可以获得指向你想要的方向的光线.
您只需要从摄像机位置延伸该光线,直到光线尖端的z坐标为零.
你可以这样做:
var vec = new THREE.Vector3(); // create once and reuse
var pos = new THREE.Vector3(); // create once and reuse
vec.set(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
0.5 );
vec.unproject( camera );
vec.sub( camera.position ).normalize();
var distance = - camera.position.z / vec.z;
pos.copy( camera.position ).add( vec.multiplyScalar( distance ) );
Run Code Online (Sandbox Code Playgroud)
变量pos是3D空间中的点的位置,"鼠标下方"和平面中的位置z=0.
编辑:如果您需要"在鼠标下"和平面中的点z = targetZ,请将距离计算替换为:
var distance = ( targetZ - camera.position.z ) / vec.z;
Run Code Online (Sandbox Code Playgroud)
three.js r.98
KTC*_*TCO 14
当使用时这对我有用orthographic camera
let vector = new THREE.Vector3();
vector.set(
(event.clientX / window.innerWidth) * 2 - 1,
- (event.clientY / window.innerHeight) * 2 + 1,
0,
);
vector.unproject(camera);
Run Code Online (Sandbox Code Playgroud)
WebGL 三.js r.89
在r.58中,这段代码对我有用:
var planeZ = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
var mv = new THREE.Vector3(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1,
0.5 );
var raycaster = projector.pickingRay(mv, camera);
var pos = raycaster.ray.intersectPlane(planeZ);
console.log("x: " + pos.x + ", y: " + pos.y);
Run Code Online (Sandbox Code Playgroud)
下面是我根据 WestLangley 的回复编写的 ES6 类,它在 THREE.js r77 中非常适合我。
请注意,它假设您的渲染视口占据整个浏览器视口。
class CProjectMousePosToXYPlaneHelper
{
constructor()
{
this.m_vPos = new THREE.Vector3();
this.m_vDir = new THREE.Vector3();
}
Compute( nMouseX, nMouseY, Camera, vOutPos )
{
let vPos = this.m_vPos;
let vDir = this.m_vDir;
vPos.set(
-1.0 + 2.0 * nMouseX / window.innerWidth,
-1.0 + 2.0 * nMouseY / window.innerHeight,
0.5
).unproject( Camera );
// Calculate a unit vector from the camera to the projected position
vDir.copy( vPos ).sub( Camera.position ).normalize();
// Project onto z=0
let flDistance = -Camera.position.z / vDir.z;
vOutPos.copy( Camera.position ).add( vDir.multiplyScalar( flDistance ) );
}
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用该类:
// Instantiate the helper and output pos once.
let Helper = new CProjectMousePosToXYPlaneHelper();
let vProjectedMousePos = new THREE.Vector3();
...
// In your event handler/tick function, do the projection.
Helper.Compute( e.clientX, e.clientY, Camera, vProjectedMousePos );
Run Code Online (Sandbox Code Playgroud)
vProjectedMousePos 现在包含 z=0 平面上的投影鼠标位置。