Skip to content

Commit

Permalink
Mesh utils
Browse files Browse the repository at this point in the history
Center at target
  • Loading branch information
jasonsturges committed Nov 24, 2024
1 parent 61dc35e commit 37d8c2f
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/utils/MeshUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,19 @@ export function centerMesh<T extends Mesh>(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<T extends Mesh>(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.
*/
Expand All @@ -28,3 +40,17 @@ export function centerMeshGeometry<T extends Mesh>(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<T extends Mesh>(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);
}
}

0 comments on commit 37d8c2f

Please sign in to comment.