Three.js 不准确的射线投射器(Raycaster)

4
我正在尝试检测对我的平面网格的点击。我使用示例设置了一个 Raycaster。
以下是代码: http://jsfiddle.net/BAR24/o24eexo4/2/ 当您单击标记线下方时,尽管点击在平面内,但不会检测到任何点击(标记线没有效果)。
同时尝试调整窗口大小。然后,即使在标记线上方的点击也可能无法正常工作。
也许这与使用正交相机有关?或者是由于未更新某些必需矩阵?
function onMouseDown(event) {
  event.preventDefault();

  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  //console.log("x: " + mouse.x + ", y: " + mouse.y);

  raycaster.setFromCamera(mouse, camera)

  var intersects = raycaster.intersectObjects(objects);

  if (intersects.length > 0) {
    console.log("touched:" + intersects[0]);
  } else {
    console.log("not touched");
  }
}
2个回答

6
你的CSS会影响射线投射计算。你可以做的一件事是设置。
body {
    margin: 0px;
}

欲了解更多信息,请参见添加div后,THREE.js射线相交失败

您还需要正确处理窗口大小调整。典型的模式如下:

function onWindowResize() {

    var aspect = window.innerWidth / window.innerHeight;

    camera.left   = - frustumSize * aspect / 2;
    camera.right  =   frustumSize * aspect / 2;
    camera.top    =   frustumSize / 2;
    camera.bottom = - frustumSize / 2;

    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

学习three.js的例子。特别是查看http://threejs.org/examples/webgl_interactive_cubes_ortho.html

此外,阅读this answer,其中描述了如何正确实例化正交相机。

three.js r.80


看起来它修复了小提琴的例子。明天将在我的程序上进行测试。谢谢! - BAR

0

试试这个... 它可以在任何地方工作,即使你有边距和滚动!

function onMouseDown(event) {
      event.preventDefault();

      var position = $(WGL.ctx.domElement).offset(); // i'm using jquery to get position 
      var scrollUp = $(document).scrollTop();
      if (event.clientX != undefined) {
           mouse.x = ((event.clientX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
           mouse.y = - ((event.clientY - position.top + scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
      } else {
           mouse.x = ((event.originalEvent.touches[0].pageX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
           mouse.y = - ((event.originalEvent.touches[0].pageY + position.top - scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
      }

      raycaster.setFromCamera(mouse, camera)
      var intersects = raycaster.intersectObjects(objects);  
    }

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