Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute bounding box after using ObjLoader three.js

I'm running into an issue trying to get the bounding box of the geometry of a model after it is loaded with the OBJLoader. So far I have:

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

But the bBox is undefined when I write it to the console. Is geometry not the right property to access in this case?

like image 605
shadyhill Avatar asked Apr 28 '26 07:04

shadyhill


2 Answers

I think something like this should do the trick:

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

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

        if ( child instanceof THREE.Mesh ) {

            child.geometry.computeBoundingBox();

        }

    }

}
like image 120
mrdoob Avatar answered Apr 29 '26 22:04

mrdoob


This answer combines the last for the newest version of 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
    }
});
};

Now you can access the dimensions of the mesh by typing object.bBox.max.x to get x for instance.

like image 33
Leon Avatar answered Apr 29 '26 21:04

Leon