diff --git a/src/utils/MeshUtils.ts b/src/utils/MeshUtils.ts index 921e9ad..13c4fd0 100644 --- a/src/utils/MeshUtils.ts +++ b/src/utils/MeshUtils.ts @@ -15,7 +15,19 @@ export function centerMesh(mesh: T): void { } /** - * Centers the geometry of the given mesh at the local origin (0, 0, 0) by modifying the geometry vertices. + * Centers a Mesh at the specified target position. + */ +export function centerMeshAtTarget(mesh: T, target = new Vector3(0, 0, 0)) { + const box = new Box3().setFromObject(mesh); + const currentCenter = new Vector3(); + box.getCenter(currentCenter); + + const offset = new Vector3().subVectors(target, currentCenter); + mesh.position.add(offset); +} + +/** + * Centers the geometry of the Mesh at the local origin (0, 0, 0) by modifying the geometry vertices. * This method moves the geometry itself so that its center is at the local origin, * without affecting the position, rotation, or scale of the mesh. */ @@ -28,3 +40,17 @@ export function centerMeshGeometry(mesh: T): void { mesh.geometry.translate(-center.x, -center.y, -center.z); } } + +/** + * Centers the geometry of a Mesh at the specified target position. + */ +export function centerMeshGeometryAtTarget(mesh: T, target = new Vector3(0, 0, 0)) { + mesh.geometry.computeBoundingBox(); + const box = mesh.geometry.boundingBox; + + if (box) { + const center = box.getCenter(new Vector3()); + const offset = new Vector3().subVectors(target, center); + mesh.geometry.translate(offset.x, offset.y, offset.z); + } +}