在 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屋!