调试threejs射线投射的鼠标坐标

5

我制作了一个射线投射器,用于在画布内部与某些对象相交。如果画布独立于浏览器窗口,则它可以正常工作,但是如果我将画布放入其他GUI中,则无法获取相交。我认为这是鼠标坐标的问题。如何调试它?如果我知道鼠标坐标,如何理解画布的坐标?

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};    
}
1个回答

7
你需要做的是:
// 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));

你需要使用 mouseVector 进行交叉检测。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接