brainydexter
brainydexter

Reputation: 20386

convert mouse click to 3d space with orthographic camera

Three.js : rev 73

I'm using the following construct to find intersection of mouse click with objects in the 3d world (orthographic setup):

function onDocumentMouseDown(event) {
  event.preventDefault();
  console.log("Click");

  var mouse = new THREE.Vector2();
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  var raycaster = new THREE.Raycaster();
  // update the picking ray with the camera and mouse position	
  raycaster.setFromCamera(mouse, camera);

  // calculate objects intersecting the picking ray
  var intersects = raycaster.intersectObjects(scene.children);

  console.log("intersects: " + intersects.length);

  for (var i = 0; i < intersects.length; i++) {
    console.log(intersects[i].point);
  }

}

However, the intersection is very inaccurate. Intersection is captured when I click near the top left of the box only.

jsFiddle: Can someone please help me understand why is this misbehaving ?

Also, if no object is being selected, I want to find out where is the click in 3d world relative to the box - left, right, below the box ? Can I use the ray itself to compute this ?

Upvotes: 2

Views: 757

Answers (1)

Nukes
Nukes

Reputation: 239

you have to get accurate mouse position for ray-casting :-

  mouse.x = ( (event.clientX -renderer.domElement.offsetLeft) / renderer.domElement.width ) * 2 - 1;
   mouse.y = -( (event.clientY - renderer.domElement.offsetTop) / renderer.domElement.height ) * 2 + 1;

you have to fire event listener when window resize i update the fiddle again check it now . add new function for window resize... code is self explaintory ...hope you got it .

Check Update Fiddle now

updated fiddle :- http://jsfiddle.net/gc1v0rza/5/

Upvotes: 3

Related Questions