Search code examples
3dthree.js

threejs get center of object


I have trying to retrieve and plot the centerpoint of some objects but I keep getting the same value for all my objects which is x=0, y=0 and z=0. So my centerpoint is always the centerpoint of the scene. I'm currently reading up on 3D computer matrixes so I'm a bit novice in this area. Do I need to update the scene somehow or update some matrix after every added object or something?

function initBoxes(){
    var box = new THREE.Mesh(geometry, material);
    box.position.set(0, 2, 2);
    getCenterPoint(box);

    var box2 = new THREE.Mesh(geometry, material);
    box2.position.set(0, 6, 6);
    getCenterPoint(box2);
}

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;

    return middle;
}

Solution

  • 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;
    }