在THREE.js中检测单击的对象 [英] Detect clicked object in THREE.js
问题描述
我在THREE.js场景中出现了很多元素,我需要检测用户单击的对象.
I have a THREE.js scene where a lot of elements appear, and I need to detect what object the user is clicking on.
到目前为止,我已经做了以下工作.摄像头不会移动太多-它只会将垂直位置更改有限的数量,始终朝着同一点.我的近似方法如下:
What I have done so far is the following. The camera does not move to much - it only changes the vertical position by a limited amount, always looking towards the same point. My approximate method is the following:
- 如果点击是相对于画布的,我就是坐标
- 我通过简单的缩放将它们转换为webGL场景中的水平和垂直坐标,并添加足够远的Z坐标.
- 我从上面的点开始拍摄水平射线,该射线由THREE.Ray()构造
- 我使用ray.intersectObjects()查找沿射线的第一个元素.
此方法大致可行,但有时距离实际点只有几个像素.
This method approximately works, but it is sometimes a few pixels away from the actual point.
是否有更可靠的技术来找出用户单击的对象?
Is there a more reliable technique to find out the object where a user has clicked?
推荐答案
取决于您使用的相机类型.
1) PerspectiveCamera :是 Mr.doob 提供的确定链接.
2) OrthographicCamera :完全不同:
1) PerspectiveCamera: is ok link that Mr.doob provides.
2) OrthographicCamera: is quite different:
var init = function() {
camera = new THREE.OrthographicCamera( SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, NEAR, FAR);
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
}
function onDocumentMouseDown( e ) {
e.preventDefault();
var mouseVector = new THREE.Vector3();
mouseVector.x = 2 * (e.clientX / SCREEN_WIDTH) - 1;
mouseVector.y = 1 - 2 * ( e.clientY / SCREEN_HEIGHT );
var raycaster = projector.pickingRay( mouseVector.clone(), camera );
var intersects = raycaster.intersectObject( TARGET );
for( var i = 0; i < intersects.length; i++ ) {
var intersection = intersects[ i ],
obj = intersection.object;
console.log("Intersected object", obj);
}
}
这篇关于在THREE.js中检测单击的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!