Hello everyone !
I am starting on React Three Fiber and I am doing a project in wich there is a GLTF model (exported from Blender) on screen made of multiple mesh’s. So, its a group.
I would be able to center the camera on it, on click.
I tried changing camera position this way:
let pos = ModernChairRef.current.children[1].position;
camera.position.set(pos.x, pos.y, pos.z);
The thing is, I would like that all mesh’s in group are visible on camera (not just a single mesh)… can I do something like “casting” a group to a mesh and get its position ?
Or do I have to iterate by every mesh and get its position and then calculate the total position ?
By “calculate” I mean, get the top position from the uppest mesh, the bottom position from the lower mesh, etc…
Thank you very much !
When you have a GLTF model made of several meshes (a group) and you want to center the camera so that the entire model is visible, you cannot simply “cast” the group to a mesh to get one position. Instead, you should compute the bounding box of the group. Three.js provides the THREE.Box3 class, which can compute a box that contains all the meshes within a group. This approach automatically iterates over all the children so you don’t have to manually loop through each mesh.
Here’s how you can do it:
- Compute the bounding box:
Use new THREE.Box3().setFromObject(group)
to compute a box that fully encloses your model (the group).
- Get the center and size:
box.getCenter(new THREE.Vector3())
returns the center of the bounding box.
box.getSize(new THREE.Vector3())
gives you the dimensions (width, height, depth).
- Position the camera:
Once you have the center and the size of the group, you can determine a suitable distance for the camera. For example, you can use the largest dimension (or the bounding sphere computed from the box) along with the camera’s field of view (FOV) to calculate a proper camera distance. A common formula is:
const box = new THREE.Box3().setFromObject(ModernChairRef.current);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
const fov = camera.fov * (Math.PI / 180); // convert FOV to radians
const cameraZ = Math.abs((maxDim / 2) / Math.tan(fov / 2));
camera.position.set(center.x, center.y, cameraZ);
camera.lookAt(center);
This calculation sets the camera at a distance so that the entire bounding box fits in the view.
4. Using Helpers:
Tools like Drei’s <Bounds>
or <Center>
components can help automate this process in React Three Fiber.
This approach ensures that you’re computing the overall bounds of your entire model rather than picking a single mesh’s position.
Thank you very much for your help !
Yes, I am currently using react-three/drei.
I will dive into the info you gently gave me and search how <Bounds>
could make the process easier.
Thanks once more !