0
votes

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?

1

1 Answers

3
votes

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;