2016-06-14 92 views
1

使用three.js,是否有一種快速且經濟的方法來檢查點/ Vector3是否位於相機的視野內?three.js:如何判斷Vector3是否在相機視圖內?

我希望創建一個盒子的網格來填充場景的「底面」,但只限於不會平移或旋轉的可見區域的邊緣(或者至少每個盒子的原點是在可見區域,剩菜剩下視線)。作爲獎勵,限制盒子可以「活」的相機位置的深度也可能是好的。

儘管目前我無法找到明確的答案,但可能只是因爲缺少正確的術語需要找到正確的答案。澄清和一個快速的例子是值得歡迎的。

入門代碼:

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>

回答

2

將相機截爲this answer

隨後指出,調用

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

編輯:全部更新例如基於問題AB OVE:

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>

相關問題