Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug threejs raycaster mouse coordinates

I made a raycaster to intersect some object inside canvas. It works good if canvas is alone in the window browser but it doesn't get intersection if I put canvas inside some other GUI and so the position of canvas is different. I think it is a problem with mouse coordinates. How can I debug it? If I know mouse coordinates how can I understand what is the coordinate of canvas?

function getPosition(event) {
// TODO: add the border of the canvas
var x = new Number();
var y = new Number();

if (event.x != undefined && event.y != undefined) {
      x = event.x;
      y = event.y;
 } else {
      // Firefox method to get the position
      x = event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
 }

 x -= canvas.offsetLeft;
 y -= canvas.offsetTop;

 return {x: x, y: y};    
}
like image 686
Stefano Maglione Avatar asked Apr 22 '15 21:04

Stefano Maglione


1 Answers

what you need to is:

// getBoundingClientRect() returns the element's position relative to the browser's visible viewport.
// clientX/Y returns the mouse position relative to the browser's visible viewport.
// we then just have to find the difference between the two to get the mouse position in "canvas-space"

var canvasPosition = renderer.domElement.getBoundingClientRect();

var mouseX = event.clientX - canvasPosition.left;
var mouseY = event.clientY - canvasPosition.top;

var mouseVector = new THREE.Vector2 (
        2 * (mouseX / window.innerWidth) - 1,
    1 - 2 * (mouseY / window.innerHeight));

and you use mouseVector for intersection.

like image 59
gaitat Avatar answered Sep 20 '22 06:09

gaitat