Three.js: Rotate at center of an object

13,678

Solution 1

You may define the coordinates of the center.

mesh.position.set( center.x, center.y, center.z );
mesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( -center.x, -center.y, -center.z ) );

Solution 2

The really easy way is to just position your cubes slightly differently, so instead of setting

mesh1.position.x = 50;
mesh2.position.x = 100;

and leaving mesh3 to default to an x of 0, you can set them like this:

mesh1.position.x = -50;
mesh3.position.x = 50;

Which will make the center box also be at the center of the scene.

jsFiddle showing it working.

Share:
13,678
jim smith
Author by

jim smith

Updated on June 15, 2022

Comments

  • jim smith
    jim smith almost 2 years

    I've modified this single spinning cube so that it contain 3 cubes in an Object3D

    http://jsfiddle.net/VsWb9/1243/

    In the above example it uses the first cube. I need it to rotate on a single axis at the exact center of the object.

    The object3D code

      geometry = new THREE.CubeGeometry(50, 50, 50);
        material = new THREE.MeshNormalMaterial();
        mesh = new THREE.Object3D();
        mesh1 = new THREE.Mesh(geometry, material);
        mesh1.position.x = 50;
        mesh2 = new THREE.Mesh(geometry, material);
        mesh2.position.x = 100;
        mesh3 = new THREE.Mesh(geometry, material);
    
        mesh.add(mesh1);
        mesh.add(mesh2);
        mesh.add(mesh3);
    
        scene.add(mesh);
    

    Here is the rotation

      mesh.rotation.x += 0.01;
      mesh.rotation.y += 0.02;
    

    EDIT: Just to say that this is an example to demonstrate the problem, my actual code object contains many different sized shapes.

  • jim smith
    jim smith almost 11 years
    I was hoping there is a recursive solution, the spinning cube in the jsfiddle is just an example...the object in my code contains loads of cubes, planes etc - I was thinking the answer may lie in getting the center xyz of the object and then somehow applying it to the rotation...
  • Ken Herbert
    Ken Herbert almost 11 years
    I would take a look at the accepted answer in this question then. It may be exactly what you need.
  • jim smith
    jim smith over 9 years
    Over a year later just googled with the same problem and found my own question as the top result! +1 this answer!