有没有办法从three.js Object3D获取边界框?

时间:2013-03-19 06:27:15

标签: three.js

我正在使用Three.js和OBJLoader.js加载OBJ文件。这将返回一个Three.Object3D对象,它具有您对3D模型的期望(位置向量,向上向量...)

我无法弄清楚如何获得它的边界框 - 这可能吗?

4 个答案:

答案 0 :(得分:65)

你不需要迭代对象的所有孩子;库中有一个方法可以执行此操作:THREE.Box3#setFromObjectsee the docs。例如,你可以这样做:

var bbox = new THREE.Box3().setFromObject(obj);

获取obj的边界框,包括其所有子项,并考虑任何翻译,轮换等。

请注意,BoundingBox帮助程序用于在场景中绘制边界框,而不仅仅是计算某个对象的边界框。

答案 1 :(得分:27)

如果您希望边界框位置和大小作为对象出现在场景中,请尝试使用BoundingBoxHelper:

var helper = new THREE.BoundingBoxHelper(someObject3D, 0xff0000);
helper.update();
// If you want a visible bounding box
scene.add(helper);
// If you just want the numbers
console.log(helper.box.min);
console.log(helper.box.max);

几何体上的.boundingBox不考虑可能应用于父网格等的平移,旋转或缩放。我发现很难手动调整,但帮助器确实如此它适合你。

答案 2 :(得分:16)

对于任何形状,在其几何对象上,都有boundingBox属性。此属性包含THREE.Box3对象。此Box3个对象包含两个THREE.Vector3个对象,minmax

var geometry = new THREE.CylinderGeometry(...);
var material = new THREE.LineBasicMaterial(...);
var mesh = new THREE.Mesh(geometry, material);

var boundingBox = mesh.geometry.boundingBox.clone();
alert('bounding box coordinates: ' + 
    '(' + boundingBox.min.x + ', ' + boundingBox.min.y + ', ' + boundingBox.min.z + '), ' + 
    '(' + boundingBox.max.x + ', ' + boundingBox.max.y + ', ' + boundingBox.max.z + ')' );

对于更复杂的形状,例如从JSON Object files加载的形状,默认情况下未定义边界框属性。它必须明确计算。

var loader = new THREE.ObjectLoader();
loader.load(imagePath, function(object){

    geometry = object.children[0].children[0].geometry;  // substitute the path to your geometry

    geometry.computeBoundingBox();  // otherwise geometry.boundingBox will be undefined

    var boundingBox = geometry.boundingBox.clone();
    alert('bounding box coordinates: ' + 
        '(' + boundingBox.min.x + ', ' + boundingBox.min.y + ', ' + boundingBox.min.z + '), ' + 
        '(' + boundingBox.max.x + ', ' + boundingBox.max.y + ', ' + boundingBox.max.z + ')' );
}

答案 3 :(得分:11)

是的,你需要这样的东西:

if (object instanceof THREE.Object3D)
{
    object.traverse (function (mesh)
    {
        if (mesh instanceof THREE.Mesh)
        {
            mesh.geometry.computeBoundingBox ();
            var bBox = mesh.geometry.boundingBox;

            // compute overall bbox
            minX = Math.min (minX, bBox.min.x);
            minY = Math.min (minY, bBox.min.y);
            minZ = Math.min (minZ, bBox.min.z);
            maxX = Math.max (maxX, bBox.max.x);
            maxY = Math.max (maxY, bBox.max.y);
            maxZ = Math.max (maxZ, bBox.max.z);
        }
    });

    var bBox_min = new THREE.Vector3 (minX, minY, minZ);
    var bBox_max = new THREE.Vector3 (maxX, maxY, maxZ);
    var bBox_new = new THREE.Box3 (bBox_min, bBox_max);

    scene.add (object);
}

修改

此方法在BoundingBoxHelper()BoxHelper()可用之前