【问题标题】:three.js: How can I tell if a Vector3 is within a camera's view?three.js:如何判断 Vector3 是否在相机的视野范围内?
【发布时间】:2016-10-15 16:47:34
【问题描述】:

使用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>

【问题讨论】:

    标签: javascript camera three.js


    【解决方案1】:

    按照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>

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多