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:
- Update World Matrices: If you have modified the
position, rotation, or scale of the group or its children in the same
frame before computing the bounding box, Three.js might not have updated
their world matrices yet. Call
group.updateWorldMatrix(true, true)to force an update of the transformation matrices for the group and all of its descendants. - World Space vs. Local Space:
setFromObject()computes the bounding box in world space. If you rotate the group, the resulting axis-aligned bounding box (AABB) will grow to tightly enclose the rotated group along the world X, Y, and Z axes. - Hidden Objects: The
setFromObject()method skips objects that have theirvisibleproperty set tofalse. If you need to include invisible meshes in your bounding box calculation, you must temporarily set theirvisibleproperty totruebefore running the calculation, and then set it back tofalse.