调试threejs raycaster鼠标坐标 [英] Debug threejs raycaster mouse coordinates

查看:389
本文介绍了调试threejs raycaster鼠标坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个射线发生器,将画布内的某些物体相交。如果仅在窗口浏览器中使用画布,则效果很好,但如果将画布放在其他GUI中也不会交叉,因此画布的位置会有所不同。我认为这是鼠标坐标的问题。我该如何调试?如果我知道鼠标坐标,怎么知道画布的坐标是什么?

  function getPosition(event){
// TODO:添加画布的边框
var x = new Number();
var y = new Number();

if(event.x!= undefined&& event.y!= undefined){
x = event.x;
y = event.y;
} else {
// Firefox获取位置
的方法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};
}


解决方案

您需要做的是:

  // getBoundingClientRect()返回元素相对于浏览器可见视口的位置。 
// clientX / Y返回鼠标相对于浏览器可见视口的位置。
//我们只需要找到两者之间的差异,即可在画布空间中获得鼠标位置。

var canvasPosition = renderer.domElement.getBoundingClientRect();

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

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

,然后使用 mouseVector 作为交集。 / p>

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};    
}

解决方案

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.

这篇关于调试threejs raycaster鼠标坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆