鼠标/画布X,Y到Three.js世界X,Y,Z [英] Mouse / Canvas X, Y to Three.js World X, Y, Z

查看:223
本文介绍了鼠标/画布X,Y到Three.js世界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.

这个问题看起来像一个类似的问题,但是没有解决方案:

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.

您已经知道相机的位置.

You already know the camera position.

使用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世界X,Y,Z的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆