为什么我的光线投射不相交?

时间:2016-03-07 20:36:45

标签: three.js

我有这段代码,旨在找到用户点击的网格:

// scene and camera are defined outside of this code
var mousePoint = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var intersections;

function onClick(event) {
  mousePoint.x = event.clientX;
  mousePoint.y = event.clientY;
  raycaster.setFromCamera(mousePoint, camera);
  intersections = raycaster.intersectObjects(
    scene.children);
}

然而,每当我点击时,intersections都会以空数组的形式返回,没有任何交叉点。我做错了什么?

1 个答案:

答案 0 :(得分:0)

来自the three.js documentation for Raycaster(强调我的):

  

.setFromCamera ( coords, camera )

     

coords - 鼠标的2D坐标,标准化设备坐标(NDC)中的 --- X和Y分量应介于-1和1之间。
  camera - 光线应来自的相机

     

使用新的原点和方向更新光线。

因此,在设置mousePoint的坐标时,不应将xy直接设置为event.clientXevent.clientY,而应将其转换为此坐标空间:

// calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
mousePoint.x = (event.clientX / window.innerWidth) * 2 - 1;
mousePoint.y = (event.clientY / window.innerHeight) * -2 + 1;