Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

threejs get center of object

Tags:

three.js

3d

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;
}
like image 574
Robert Avatar asked Jul 11 '16 11:07

Robert


1 Answers

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.

function getCenterPoint(mesh) {
    var geometry = mesh.geometry;
    geometry.computeBoundingBox();
    var center = new THREE.Vector3();
    geometry.boundingBox.getCenter( center );
    mesh.localToWorld( center );
    return center;
}
like image 186
Wilt Avatar answered Nov 03 '22 05:11

Wilt