在 THREE.js 中检测点击的对象
我有一个 THREE.js 场景,其中出现了很多元素,我需要检测用户正在单击的对象。
到目前为止我所做的如下。相机不会移动太多 - 它只会有限度地改变垂直位置,始终朝向同一点。我的近似方法如下:
- 如果相对于画布单击,我会获取坐标,
- 通过简单的重新缩放将它们转换为 webGL 场景中的水平和垂直坐标,并添加一个足够远的 Z 坐标。
- 我从上面的点开始采用一条由 THREE.Ray() 构造的水平射线,
- 我使用 ray.intersectObjects() 来查找沿射线的第一个元素。
此方法大致有效,但有时与实际点相差几个像素。
是否有更可靠的技术来找出用户单击的对象?
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:
- I take the coordinates if the click relative to the canvas
- I translate them into horizontal and vertical coordinates in the webGL scene by means of a simple rescaling, and add a Z coordinate which is sufficiently far away.
- I take a horizontal ray starting from the point above, constructed by THREE.Ray()
- I use ray.intersectObjects() to find the first element along the ray.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
取决于您使用的相机类型。
1) PerspectiveCamera:是 Mr.doob 提供的链接。
2) OrthographicCamera:有很大不同:
Depends on what kind of camera are you using.
1) PerspectiveCamera: is ok link that Mr.doob provides.
2) OrthographicCamera: is quite different:
看看这个:
Check out this one:
检查鼠标与 3d 空间中任何立方体的交集并更改其颜色。也许这对您有帮助。
Checks for intersection of the mouse and any of the Cubes in 3d space and alters it's color. Maybe this help you.
我在尝试对不占据屏幕整个宽度和高度的画布实现此操作时遇到了问题。这是我发现效果很好的解决方案。
初始化现有画布上的所有内容:
向画布添加事件侦听器:
或者对于“touchstart”事件,将计算 mouse.x 和 mouse.y 的行更改为:
I ran into problems trying to implement this for a canvas which does not take up the entire width and height of the screen. Here is the solution I found works quite well.
Initialize everything on an existing canvas:
Add an event listener to the canvas:
Or for a 'touchstart' event, change the lines calculating the mouse.x and mouse.y into: