Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a THREE.Group based on the width of its children?

Tags:

three.js

I am using Three.js (r86) to render a group of spheres. I'm doing this by calling a createSphereGroup function from an external library:

// External library code.
function createSphereGroup(sphereCount) [
  var group = new THREE.Group();
  for (var i = 0; i < sphereCount; i++) {
    var geometry = new THREE.SphereGeometry(50);
    var material = new THREE.MeshPhongMaterial({ color: 0xFF0000 });
    var sphere = new THREE.Mesh(geometry, material);
    sphere.position.x = i * 150;
    group.add(sphere);
  }
  return group;
}

(Assume that the external library is opaque and I can't modify any code in it.)


// My code.
var group = createSphereGroup(5);
scene.add(group);

...which looks like this:

Screenshot

As you can see, the group of spheres is off-center. I would like the group to be centered, with the 3rd sphere to be at the point where the two lines intersect (x=0).

So is there some way that I can center the group? Maybe by computing the width of the group and then positioning it at x=-width/2? I know you can call computeBoundingBox on a geometry to determine its width, but a THREE.Group doesn't have a geometry, so I'm not sure how to do this...

like image 539
XåpplI'-I0llwlg'I - Avatar asked Nov 28 '22 22:11

XåpplI'-I0llwlg'I -


1 Answers

If you want to center an object (or group) and its children, you can do so by setting the object's position like so:

new THREE.Box3().setFromObject( object ).getCenter( object.position ).multiplyScalar( - 1 );

scene.add( object );

three.js r.92

like image 60
WestLangley Avatar answered Dec 21 '22 23:12

WestLangley