Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Three.js 加载对象后的threejs重新居中摄像头_Three.js - Fatal编程技术网

Three.js 加载对象后的threejs重新居中摄像头

Three.js 加载对象后的threejs重新居中摄像头,three.js,Three.js,加载多个gltf文件后,我将重命名这些文件,并尝试重新定位摄影机,使其居中,并查看新对象的质心,整个场景适合摄影机 但定心并不总是有效的,有时质心是在完全不同的地方计算出来的。以下代码仅在加载所有对象后在render()中运行一次: var all_centers = []; scene.updateMatrixWorld(); scene.traverse(function(child){ if (child instanceof THREE.Mesh){ if (ch

加载多个gltf文件后,我将重命名这些文件,并尝试重新定位摄影机,使其居中,并查看新对象的质心,整个场景适合摄影机

但定心并不总是有效的,有时质心是在完全不同的地方计算出来的。以下代码仅在加载所有对象后在
render()
中运行一次:

var all_centers = [];
scene.updateMatrixWorld();
scene.traverse(function(child){
    if (child instanceof THREE.Mesh){
        if (child.name.indexOf("_") !== -1){ // the newly imported objects                          
            child.geometry.computeBoundingSphere();
            var the_center = new THREE.Vector3();
            child.getWorldPosition(the_center); 
            all_centers.push(the_center);               
        }
    }
});
var the_centroid = getPointsCentroid(all_centers);
var cameraPosition = new THREE.Vector3(the_centroid.x,the_centroid.y,-55);
camera.position.copy(cameraPosition);
camera.lookAt(the_centroid);
这是质心的函数:

function getPointsCentroid(points){
    var centroid = [0.,0.,0.];
    for(var i = 0; i < points.length; i++) {
        var point = points[i];
        centroid[0] += point.x;
        centroid[1] += point.y;
        centroid[2] += point.z;
    }
    centroid[0] /= points.length;
    centroid[1] /= points.length;
    centroid[2] /= points.length;
  return new THREE.Vector3(centroid[0],centroid[1],centroid[2]);
}
函数getPointsCentroid(点){ 变量质心=[0,0,0.]; 对于(变量i=0;i现在忽略了让整个场景适合摄影机的问题(这是一个常见问题,我相信你可以在网上找到有用的信息(也许?)

相反,让我们把重点放在您的主要问题上:您希望找到一组对象的中心。您当前正在做的是计算对象中心的平均值。这意味着,如果最左侧有一个对象,最右侧有9个对象,则计算的中心点也将位于最右侧。(假设对象具有相似的质量,这将是质心的近似值。)

但是,为了使相机居中,使每个对象都可见,您对质心不感兴趣,但希望找到一个点,使到最左侧点的距离等于到最右侧点的距离,同样地,从最低到最高点的距离,等。可以使用所有对象的。此边界框的中心是要查找的点

如果要将相机与轴对齐,可以轻松地为每个对象计算这样的边界框,如下所示:

new THREE.Box3().setFromObject(myMesh)
所有对象的边界框只是由您计算的所有对象边界框的最低和最高坐标表示的框。完整边界框的中心将为您提供所需的点

接下来,假设摄影机与轴对齐,问题只是找到从摄影机到该点的适当距离,以便整个边界框适合视口