Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect clicked object in 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:

  • 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?

like image 736
Andrea Avatar asked Sep 06 '25 09:09

Andrea


1 Answers

Depends on what kind of camera are you using.

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);
  }
}
like image 166
Luca Davanzo Avatar answered Sep 09 '25 05:09

Luca Davanzo