Reputation: 865
I'm currently centering objects/models (mesh) in my scene by calling mesh.geometry.center()
This helps me place the object in the center based on its bounding box.
This works perfectly for static objects that don't ever change size (for example lets say I want to render a cardboard box and I'll never change its proportions).
However, I also have some complex 3D models (for example - a bowling ball, a couple of jagged rocks and the Eiffel Tower).
At the moment, each of these models will be placed centrally based on its bounding box. This means that the jaggedy points of the rocks, the curved base of the bowling ball, or the first section of the base of the Eiffel Tower will jut through / clip through the base of the cardboard box (or, conversely, if not scaled appropriately, will just float in mid-air)
What I need is a way find the center of each mesh on only the X and Y axis to allow me to place these models flat on an XY plane without having to manually adjust the Z value. Is this possible?
Upvotes: 0
Views: 2825
Reputation: 4340
BufferGeometry
has a center
method which center the geometry based on the bounding box. But it also center the object in z axis which you want to avoid. Below is a modified center
method that center on x & y axis only.
// scale, change dimension of yourMesh
// ..
const geometry = yourMesh.geometry;
geometry.computeBoundingBox();
const centerVector = new Vector3();
geometry.boundingBox.getCenter(centerVector).negate();
geometry.translate(centerVector.x, centerVector.y, 0);
Upvotes: 0
Reputation: 5036
A general way to do this for objects or trees of objects... Here I get the bounds of the object.. then scale it so it ranges to 1 on the largest axis... and centers it on x,z axis, and seated on the y.
var cent = new THREE.Vector3();
var size = new THREE.Vector3();
var bbox = new THREE.Box3().setFromObject(yourObject);
bbox.getCenter(cent);
bbox.getSize(size);
//Rescale the object to normalized space
var maxAxis = Math.max(size.x, size.y, size.z);
yourObject.scale.multiplyScalar(1.0 / maxAxis);
//Now get the updated/scaled bounding box again..
bbox.setFromObject(yourObject);
bbox.getCenter(cent);
bbox.getSize(size);
yourObject.position.x = -cent.x;
yourObject.position.y = 0;
yourObject.position.z = -cent.z;
Upvotes: 3