鼠标/画布 X、Y 到 Three.js World X、Y、Z [英] Mouse / Canvas X, Y to Three.js World X, Y, Z
问题描述
我四处寻找与我的用例相匹配的示例,但找不到.我正在尝试将屏幕鼠标坐标转换为考虑到相机的 3D 世界坐标.
I've searched around for an example that matches my use case but cannot find one. I'm trying to convert screen mouse co-ordinates into 3D world co-ordinates taking into account the camera.
我发现的所有解决方案都是通过光线交叉来实现对象拾取.
Solutions I've found all do ray intersection to achieve object picking.
我想要做的是将 Three.js 对象的中心定位在鼠标当前悬停"的坐标上.
What I am trying to do is position the center of a Three.js object at the co-ordinates that the mouse is currently "over".
我的相机位于 x:0、y:0、z:500(虽然它会在模拟过程中移动)并且我的所有对象都位于 z = 0 且 x 和 y 值不同,所以我需要知道世界 X, Y 基于对将跟随鼠标位置的对象假设 az = 0.
My camera is at x:0, y:0, z:500 (although it will move during the simulation) and all my objects are at z = 0 with varying x and y values so I need to know the world X, Y based on assuming a z = 0 for the object that will follow the mouse position.
这个问题看起来像一个类似的问题,但没有解决方案:在THREE.js中获取鼠标相对于3D空间的坐标
This question looks like a similar issue but doesn't have a solution: Getting coordinates of the mouse in relation to 3D space in THREE.js
鉴于鼠标在屏幕上的位置范围为左上角 = 0, 0 | 右下角 = window.innerWidth, window.innerHeight",任何人都可以提供将 Three.js 对象移动到鼠标的解决方案沿 z = 0 的坐标?
Given the mouse position on screen with a range of "top-left = 0, 0 | bottom-right = window.innerWidth, window.innerHeight", can anyone provide a solution to move a Three.js object to the mouse co-ordinates along z = 0?
推荐答案
您的场景中不需要任何对象即可执行此操作.
You do not need to have any objects in your scene to do this.
您已经知道相机位置.
使用vector.unproject(camera)
,您可以获得指向您想要的方向的光线.
Using vector.unproject( camera )
you can get a ray pointing in the direction you want.
您只需要从相机位置延伸该射线,直到射线尖端的 z 坐标为零.
You just need to extend that ray, from the camera position, until the z-coordinate of the tip of the ray is zero.
你可以这样做:
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 ) );
变量pos
是点在3D空间、鼠标下"和平面z=0
中的位置.
The variable pos
is the position of the point in 3D space, "under the mouse", and in the plane z=0
.
如果您需要鼠标下方"和平面 z = targetZ
中的点,请将距离计算替换为:
If you need the point "under the mouse" and in the plane z = targetZ
, replace the distance computation with:
var distance = ( targetZ - camera.position.z ) / vec.z;
three.js r.98
three.js r.98
这篇关于鼠标/画布 X、Y 到 Three.js World X、Y、Z的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!