three.js:如何判断 Vector3 是否在相机的视野内?

three.js: How can I tell if a Vector3 is within a camera's view?

使用 three.js,是否有一种快速且成本低廉的方法来检查 point/Vector3 是否在相机的视野内?

我希望创建一个方框网格来填充场景的 "floor",但仅限于不会平移或旋转的可见区域的边缘(或至少是原点每个盒子都在可见区域,剩菜悬在视线之外)。作为奖励,限制盒子可以 "live" 进入的摄像机位置的深度也可能很好。

虽然我目前无法找到明确的答案,但这可能只是因为缺少找到正确答案所需的正确术语。欢迎澄清和举个简单的例子。

起始代码:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var vec = new THREE.Vector3(0, 0, 10);
          
//??? How to tell if Vector3 is within camera's view?

var renderer = new THREE.WebGLRenderer();
document.body.appendChild( renderer.domElement );

console.log('Yes it is just a black/blank screen at this point.');
body { margin: 0; }
canvas { width: 100%; height: 100% }
<html>
<head>
<meta charset=utf-8>
<title>Spot the Vector</title>
</head>
<body>
<script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.min.js"></script>
</body>
</html>

采用this answer

中所述的相机平截头体

然后,致电

if(frustum.containsPoint( vec ))  
    { ...

编辑:基于上述问题的完整更新示例:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

//var vec = new THREE.Vector3(0, 0, 10); //behind camera
var vec = new THREE.Vector3(0, 0, -10); //in front of camera

//check if within camera's view:
camera.updateMatrix(); // make sure camera's local matrix is updated
camera.updateMatrixWorld(); // make sure camera's world matrix is updated
camera.matrixWorldInverse.getInverse( camera.matrixWorld );

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

if(frustum.containsPoint(vec)) {
  console.log('within camera view');
} else {
  console.log('outside camera view');
}

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
body { margin: 0; }
canvas { width: 100%; height: 100% }
<html>
  <head>
    <meta charset=utf-8>
    <title>Spot the Vector</title>
  </head>
  <body>
    <script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.min.js"></script>
  </body>
</html>