three.js - 检查对象是否仍然在相机视野中

Nic*_*ick 6 javascript camera fieldofview three.js

使用2D画布时,如果要检查某些内容是否不再"在屏幕上",您只需执行以下操作:

if( pos.x > window.innerWidth || pos.x < 0 ||
    pos.y > window.innerHeight || pos.y < 0 ) {
    // has left the screen
}
Run Code Online (Sandbox Code Playgroud)

我如何在three.js场景中检查某些内容是否仍在"屏幕上"(在相机视图中)?

小智 11

而不是检查2d画布,你可以检查3d点是否是平截头体.

camera.updateMatrix();
camera.updateMatrixWorld();
var frustum = new THREE.Frustum();
frustum.setFromMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));  

// Your 3d point to check
var pos = new THREE.Vector3(x, y, z);
if (frustum.containsPoint(pos)) {
    // Do something with the position...
}
Run Code Online (Sandbox Code Playgroud)


rag*_*-wd 8

const frustum = new THREE.Frustum()
const matrix = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
frustum.setFromProjectionMatrix(matrix)
if (!frustum.containsPoint(obj.position)) {
    console.log('Out of view')
}
Run Code Online (Sandbox Code Playgroud)

在勾选函数中使用它,以便当对象离开相机视图时它会更新您。

注意:在新版本的 Three.js 中,setFromMatrix() 已更改为 setFromProjectionMatrix()

  • 这比 @congle 的答案更新。 (2认同)