Get center of object

I encountered problem, – when clicking on some object in scene, camera must center on this object. For this i need center coordinates of object (y axis). How i can compute this? Tried to sum all vertices of this object and divide it on vertices count, but this, of course, wrong decision.

Author: Fantashit

3 thoughts on “Get center of object

  1. You can get center of geometry bounding box:

    geometry.computeBoundingBox();
    
    var centerX = 0.5 * ( geometry.boundingBox.x[ 1 ] - geometry.boundingBox.x[ 0 ] );
    var centerY = 0.5 * ( geometry.boundingBox.y[ 1 ] - geometry.boundingBox.y[ 0 ] );
    var centerZ = 0.5 * ( geometry.boundingBox.z[ 1 ] - geometry.boundingBox.z[ 0 ] );

    Then you could set your camera’s target to object position plus center:

    camera.target.position.copy( object.position );
    camera.target.position.addSelf( new THREE.Vector3( centerX, centerY, centerZ ) );
  2. var x0 = boundingBox.x[ 0 ];
    var x1 = boundingBox.x[ 1 ];
    var y0 = boundingBox.y[ 0 ];
    var y1 = boundingBox.y[ 1 ];
    var z0 = boundingBox.z[ 0 ];
    var z1 = boundingBox.z[ 1 ];

    is now:

    var x0 = boundingBox.min.x;
    var x1 = boundingBox.max.x;
    var y0 = boundingBox.min.y;
    var y1 = boundingBox.max.y;
    var z0 = boundingBox.min.z;
    var z1 = boundingBox.max.z;

    (as of r47)

  3. Conceptually, it’s adding two vectors and taking the half of the result. I’m not sure if it’s faster, but it’s more… concpetual:

            c.addVectors( 
                object.children[0].geometry.boundingBox.min,
                object.children[0].geometry.boundingBox.max
            );
    
            c.divideScalar(2);
    

Comments are closed.