How to Use Three.js Group to Organize Meshes
In Three.js, managing complex 3D scenes with numerous individual
objects can quickly become difficult to maintain. This article explains
how to use the THREE.Group class to bundle multiple meshes
together, allowing you to manipulate them as a single entity. You will
learn the basic syntax, see a practical code example, and understand how
grouping simplifies transformations like translation, rotation, and
scaling.
What is the Three.js Group Class?
The THREE.Group class is a container object that allows
you to organize your 3D scene hierarchically. It inherits from
THREE.Object3D, which means it possesses all the standard
transformation properties (position, rotation, and scale). By adding
multiple meshes to a single group, you can move, rotate, or scale the
entire group as one unit, while the individual meshes within the group
maintain their positions relative to each other.
Step-by-Step Implementation
To organize meshes using THREE.Group, follow these
steps:
- Instantiate the Group: Create a new instance of
THREE.Group. - Create Your Meshes: Define the geometries, materials, and meshes you want to group.
- Add Meshes to the Group: Use the
.add()method of the group instance to insert the meshes. - Add the Group to the Scene: Instead of adding each mesh individually to the main scene, add the group object itself.
Here is a clean code example demonstrating this process:
// 1. Create the scene
const scene = new THREE.Scene();
// 2. Create the Group
const tableGroup = new THREE.Group();
// 3. Create individual meshes (e.g., a tabletop and a leg)
const tabletopGeometry = new THREE.BoxGeometry(4, 0.2, 2);
const tabletopMaterial = new THREE.MeshBasicMaterial({ color: 0x8B4513 });
const tabletop = new THREE.Mesh(tabletopGeometry, tabletopMaterial);
tabletop.position.y = 1; // Position relative to the group's center
const legGeometry = new THREE.CylinderGeometry(0.1, 0.1, 1);
const legMaterial = new THREE.MeshBasicMaterial({ color: 0x5C4033 });
const leg = new THREE.Mesh(legGeometry, legMaterial);
leg.position.set(-1.8, 0.5, -0.8); // Position relative to the group's center
// 4. Add the meshes to the group
tableGroup.add(tabletop);
tableGroup.add(leg);
// 5. Add the group to the scene
scene.add(tableGroup);Manipulating the Group
Once your meshes are grouped, any transformations applied to the group will affect all children. For example, if you want to rotate the entire table, you only need to rotate the group:
// Rotates the tabletop and the leg together around the group's anchor point
tableGroup.rotation.y += 0.01;
tableGroup.position.x = 5;This hierarchical structure prevents the need for complex mathematical calculations to rotate or move individual parts manually, making your codebase cleaner and your animations smoother.