Get Bounding Box of a Group in Three.js

In Three.js, calculating the exact bounding box of a THREE.Group containing multiple distinct meshes requires traversing the group’s hierarchy and expanding a 3D bounding box to encompass all child geometries. This article provides a direct guide and code example on how to use the THREE.Box3 class alongside the setFromObject method to compute this bounding box accurately, accounting for all child positions, rotations, and scales.

The Standard Solution: THREE.Box3.setFromObject()

The most efficient and built-in way to calculate the bounding box of a group in Three.js is by using the THREE.Box3 class. The .setFromObject(object) method automatically traverses the specified object and all of its descendants, computing a single, unified bounding box in world space.

Here is the complete code implementation:

import * as THREE from 'three';

// 1. Instantiate the group and add multiple meshes
const group = new THREE.Group();

const cube = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial()
);
cube.position.set(-2, 0, 0);

const sphere = new THREE.Mesh(
    new THREE.SphereGeometry(1, 16, 16),
    new THREE.MeshBasicMaterial()
);
sphere.position.set(3, 2, -1);

group.add(cube);
group.add(sphere);

// 2. Update world matrices
// This step ensures that any recent transformations are computed before reading coordinates
group.updateWorldMatrix(true, true);

// 3. Compute the bounding box of the entire group
const boundingBox = new THREE.Box3().setFromObject(group);

// 4. Extract useful dimensions and positions from the bounding box
const size = new THREE.Vector3();
boundingBox.getSize(size);

const center = new THREE.Vector3();
boundingBox.getCenter(center);

console.log('Bounding Box Min:', boundingBox.min);
console.log('Bounding Box Max:', boundingBox.max);
console.log('Total Size (Width, Height, Depth):', size);
console.log('Center Point:', center);

Key Considerations for Accurate Calculations

To ensure your bounding box calculation is 100% accurate, keep the following details in mind: