3D models don't seem to have a geometry property so how can I compute a bounding box?

I have the following code in my ThreeJS scene that I use for computing the center of a 3D object, by getting its bounding box first:

    const geometry = threeJsMesh.geometry;
    geometry.computeBoundingBox();

This has worked fine for me with the cubes, planes, spheres, etc. I have created for my ThreeJS world. But I am now working with 3D models and when I tried to execute that code on a GLTF/GLB model I have in the world, I discovered that its geometry property was undefined.

So I take it that 3D models don’t have a geometry property? If so, how can I computer the bounding box of a 3D model and also its center point?

Hi,MeJayEss. This is an example of how to solve the bounding box of the model.

const gltfloader = new GLTFLoader();
gltfloader.load('yourModel.glb', gltf => {

    scene.add(gltf.scene);

    const model = gltf.scene;

    // Calculate the bounding box of the model (but no a single Mesh) so that the whole model is centered
    let box3 = new THREE.Box3();
    box3.expandByObject(model);

    // Assign the center point of the bounding box to the vector
    let center = new THREE.Vector3();
    box3.getCenter(center);

    // Reposition the model so that it is centered.
    model.position.x = model.position.x - center.x;
    model.position.y = model.position.y - center.y;
    model.position.z = model.position.z - center.z;

});

Hope it will help you

1 Like

In addition, if you want to make the bounding box visualized, here are the 2 classes already wrapped.
ThreeJs Bounding box visualization (codepen.io)

1 Like

Thanks! That was what I needed. :wink:

Here is a simple example with visualization of the box ( from the collection):
LoadGLTFmove

1 Like