threejs get center of object
The object boundingBox
is in local space. If you want the center in world space you have to translate your middle
vertex to world space. You can do that easily with the THREE.Object3D
localToWorld
method like this:
function getCenterPoint(mesh) {
var middle = new THREE.Vector3();
var geometry = mesh.geometry;
geometry.computeBoundingBox();
middle.x = (geometry.boundingBox.max.x + geometry.boundingBox.min.x) / 2;
middle.y = (geometry.boundingBox.max.y + geometry.boundingBox.min.y) / 2;
middle.z = (geometry.boundingBox.max.z + geometry.boundingBox.min.z) / 2;
mesh.localToWorld( middle );
return middle;
}
Update:
In the newer three.js versions there is a convenience method getCenter
inside the THREE.Box3
class. Since the bounding box is in local coordinate space you will need to project the result to worldspace to get the center in world coordinates, but this is easy with the localToWorld
method from the parent object.
function getCenterPoint(mesh) {
var geometry = mesh.geometry;
geometry.computeBoundingBox();
var center = new THREE.Vector3();
geometry.boundingBox.getCenter( center );
mesh.localToWorld( center );
return center;
}
try the code below:
let box = new THREE.Box3().setFromObject(myObject3D)
let sphere = box.getBoundingSphere()
let centerPoint = sphere.center
THREE.Box3().setFromObject(Object3D) will traverse the Object3D's geometries, and return their holistic bounding Box.