javascript - 移动相机使所有对象完全适合平截头体 - three.js

标签 javascript three.js intersect plane frustum

编辑:我改写了我的问题以帮助遇到同样问题的用户。

我有一个 three.js 场景,我在上面添加了一些球体。

我想将相机移向特定方向,直到所有对象(随机放置在场景中)“完全适合”用户的屏幕。

最佳答案

我找到了问题的答案!

1. 我在一个循环内移动相机(缩放到所需的方向),并且在每次重复中我使用相机的矩阵创建一个新的平截头体

2. 我检查我的任何球体是否与平截头体的平面相交。如果是这样,则意味着我的一个对象的一部分在截头锥体之外,因此我打破循环并将相机移动到它的最后位置。

以上可能也适用于任何对象(不仅是球体),因为每个对象都有一个可以计算的 boundingSphere(尽管结果可能不是很精确)。

它在缩小时也有效,您只需将相机从物体移开,直到所有平面都没有负距离(负距离意味着物体在“外面”平截头体的平面)。

代码(仅用于缩小 - r72):

var finished = false;
var camLookingAt = /* calc. */ ;

while( finished === false ){

var toDirection= camera.position.clone().sub(camLookingAt.clone());
toDirection.setLength(vec.length() - 1); // reduce length for zooming out
camera.position.set(toDirection.x, toDirection.y, toDirection.z);

camera.updateMatrix(); // make sure camera's local matrix is updated
camera.updateMatrixWorld(); // make sure camera's world matrix is updated

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

for (var j = frustum.planes.length - 1; j >= 0; j--) {  
  var p = frustum.planes[j];  
  for (var i = myMeshSpheres.length - 1; i >= 0; i--) { 
    var sphere = new THREE.Sphere(myMeshSpheres[0].position.clone(), myMeshSpheres[0].radius); 

    if( p.distanceToSphere(sphere) < 1 ){ // if is negative means part of sphere is outside plane/frustum
      finished = true; 
    } 

  } 
}  

关于javascript - 移动相机使所有对象完全适合平截头体 - three.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35156604/

相关文章:

javascript - 链表 - 删除最后一个节点

javascript - 多次调用 sagaMiddleware.run 是否安全?

javascript - Three.js computeCentroids 是做什么的?

ruby - 如何检查 Ruby 数组是否包含多个值之一?

c# - 我的 syncfunctions hashCode 使用方法是否正确?

python - 如何通过自定义比较函数找到集合交集?

javascript - 错误: bundling failed: TypeError: Cannot read property 'transformFile' of undefined, react native

javascript - 使用 Jasmine 单元测试模拟鼠标点击

javascript - 将 FBO 值投影到屏幕空间以从深度纹理中读取

javascript - 如何在 Three.js 中启用着色