简体   繁体   中英

How to rotate a group in ThreeJS around its center?

I am trying to build a working Rubikscube with ThreeJS . Now I have a problem with rotating the sides. At the moment, I am adding the smaller cubes to the Rubikscube and create it like this:

const rubikscube = new THREE.Group();
for (var i = 0; i < 27; i++) {
  // 3x3x3 (0,0,0) is on the top left corner
  var cube = createPartOfCube(i, scene);
  cube.name = i;
  cube.position.x = (i % 3) * gap;
  cube.position.y = Math.floor(i / 9) * gap;
  cube.position.z = (Math.floor(i / 3) % 3) * gap;
  rubikscube.add(cube);
}
scene.add(rubikscube);

And this all works fine until I try to rotate , eg the right side. I select the pieces on the right side and add them to their own group . Now, when I try to rotate the group, it's rotating around the x axes . Here is the method I want to use for moving a side (just ignore the bool and eval part, its just for getting the right pieces):

  function move(direction) {
    var bool = moves[direction];

    var pivot = new THREE.Group();
    pivot.updateMatrixWorld();

    for (var i = 0; i < 27; i++) {
      if (eval(format(bool, i))) {
        pivot.add(scene.getObjectByName(i));
      }
    }
    scene.add(pivot);
    animateMove(pivot);
  }

And animating it:

  function animateMove(pivot) {
    requestAnimationFrame(() => {
      animateMove(pivot);
    });
    // missing part
    renderer.render(scene, camera);
  }

What I've tried:

I have tried different methods, to rotate it the right way but nothing worked and moving the cube is also not the right answer.

One thing I tried was on this thread , but when I tried to rotate it this way, the side just moved , so it's still rotating around the x-axes .

I hope that someone understands my issue and helps me to solve it. Thanks!

All rotations take place around the object's point of origin. So if your object's position is at (0, 0, 0), then that's going to be the pivot point.

I recommend you nest your cube pieces into a THREE.Group() each, that way you can keep the pivot point constant at (0, 0, 0) for all 27 pieces. Then you can displace each piece inside its group to the desired position:

const geom = new THREE.BoxGeometry(1, 1, 1);
const Piece = new THREE.Mesh(geom, mat);
const Group = new THREE.Group();

// Nest Piece inside of its Group
Group.add(Piece);

// Parent Group position is at (0, 0, 0)
// Inner piece position is at (-1, -1, -1)
Piece.position.set(-1, -1, -1);

// Now we can apply rotations to the parent group 
// and the child will maintain its distance from the center
Group.rotation.set(Math.PI / 2, 0, 0);

You'll want to repeat this for all values of [-1, 0, +1] for X,Y,Z . That's 3^3 = 27 pieces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM