How to center an object?

In the code below, what are the different impacts on obj when using

  • box.getCenter(obj.position), and when using
  • obj.geometry.center()

If I comment one or the other I get different results but I have hard time to define the changes.

Also, if I want to see the absolute vertices of the object.geometry, I can call

   obj.updateMatrixWorld();
   for(var i=0;i<obj.geometry.vertices.length;i++){
     obj.geometry.vertices[i].applyMatrix4( obj.matrixWorld );
   }
   obj.geometry.verticesNeedUpdate = true;

In such case, do I need to reset the obj.position? (or else, the absolute vertices will get updated to new values in every frame?)

Thanks,

Avner

obj=new THREE.Mesh(
    new THREE.PlaneGeometry(3, 2, 1, 1),
    new THREE.MeshLambertMaterial({color:0x00aa00,transparent:true,side:THREE.DoubleSide})
);

obj.geometry.translate(3,2,0);
obj.position.copy(new THREE.Vector3(3.0, 2, 0.0));
var box = new THREE.Box3().setFromObject( obj );
box.getCenter( obj.position ); // this re-sets the obj position
obj.geometry.center();

The following line centers the geometry based on its bounding box.

obj.geometry.center();

If you calculate a bounding box via Box3.setFromObject(), the actual transformation of the object is taken into account. So if you scale your object via object.scale.set( 2, 2, 2 ) you will also get a larger bounding box.

What you actually mean is to calculate the vertex positions in world space. If you change an object’s transformation via Object3d.position, Object3d.rotation or Object3d.scale, you have to ensure that Object3d.matrixWorld is up to date so it reflects these values. Use Object3D.updateMatrixWorld() for this.

1 Like

Crossposting: