使用ObjLoader three.js后如何计算边界框

时间:2012-08-02 16:45:38

标签: javascript three.js

我遇到了一个问题,试图在加载OBJLoader之后获取模型几何的边界框。到目前为止,我有:

var loader = new THREE.OBJLoader();
loader.load( mURL, function ( object ) {

for ( var i = 0, l = object.children.length; i < l; i ++ ) {
    geometry = object.children[0].geometry;         
    bBox = geometry.computeBoundingBox();
    console.log("have a box of "+bBox);
}
//...rest of function

但是当我把它写到控制台时,bBox是未定义的。在这种情况下,几何体不是正确的属性吗?

4 个答案:

答案 0 :(得分:3)

我觉得这样的事情可以解决问题:

var loader = new THREE.OBJLoader();
loader.load( mURL, function ( object ) {

    THREE.SceneUtils.traverseHierarchy( object, function ( child ) {

        if ( child instanceof THREE.Mesh ) {

            child.geometry.computeBoundingBox();

        }

    }

}

答案 1 :(得分:2)

这个答案结合了最新版THREE.js的最后一个

var loader = new THREE.OBJLoader();
loader.load( mURL, function ( object ) {
object.traverse(function ( child ) {
    if ( child instanceof THREE.Mesh ) {
        child.geometry.computeBoundingBox();
        object.bBox = child.geometry.boundingBox;//<-- Actually get the variable
    }
});
};

现在,您可以通过输入object.bBox.max.x来获取网格的尺寸,例如获取x。

答案 2 :(得分:0)

基于mrdoob的遍历功能,我能够使用以下内容进入边界框:

var loader = new THREE.OBJLoader();
loader.load( mURL, function ( object ) {
    THREE.SceneUtils.traverseHierarchy(object, function(child){
    if(child instanceof THREE.Mesh){
        for (var i in child) {
            if(i == "geometry"){
                var geo = child[i];
                    geo.computeBoundingBox();
                    var bBox = geo.boundingBox;
                }
             }
         }
      });
      ///rest of loading function here
 });

答案 3 :(得分:0)

@ mrdoob的答案是正确的,但是由于三个API的更改(从r52开始),现在看起来应该是这样的:

var loader = new THREE.OBJLoader();
loader.load( mURL, function ( object ) {
    object.traverse(function ( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.geometry.computeBoundingBox();
        }
    });
};