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?
projector.unprojectVector()
. In a later version I was trying to unproject the vector myself, considering the angle it formed wrt to the camera, which I could find because I know the fov, but it did not work as expected. By the way, is there a reason why you normalize the vector before passing it to the Ray constructor? The direction does not change upon normalizing. – Andrea