Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js: Adding and Removing Children of Rotated Objects

Tags:

three.js

3d

I'm trying to simulate a rubik's cube. I wanted to choose a face at random and rotate it. So I've created 27 cube meshes and positioned them. You can see the working (erratically) rubik's cube here http://codepen.io/theonepa1/full/fzAli

What is the issue.

As you can see from the above link, the smaller cubes on the edges move in a random way (atleast not the way I expect it to be)

What I've done.

When trying to rotate a face , I've grouped 9 cubes belonging to the face added them as children to a new Object3D object. I then rotated the object3d along its axis using object3d.rotate.x (or y or z).

What I've debugged

I've made sure that the cubes I'm selecting for the second face rotation are correct. After the first face rotation is completed, I update their virtual positions (not actual coordinates). So for the second face rotation I've verified that the cubes are picked correctly.

What actually happens

One observation I made was that cubes' (smaller ones) axes are altered after the object3d (parent holding the 9 cubes of a face) is rotated. And also the cubes' coordinates are not getting auto updated after the face rotation. Say for example if one of the cube has (0,0,22) as coordinates before the face rotation, the coordinates are same even after the rotation. However the orientation of axes of the cube is changed.

What is the best way to rotate a group of objects around a axis ? Is using Object3D correct ? Are we supposed to remove the children from one parent before adding it to another group for the second face rotation ?

Do I've to do some kind of update on the individual cubes before adding them to second group for the second face rotation ?

I've read some posts about applyMatrixWorld , but I really could not understand what its effect was on the orientation of the axes and the coordinates of the cube ?

Can you let me know where can I read about the concepts like applyMatrixWorld , is it some kind of common concept in a normal 3d programming ?

Thats a really long question. Would really appreciate your reply :)

like image 531
Pavan Avatar asked Nov 20 '13 06:11

Pavan


1 Answers

The trick is to make use of THREE.Object3D.attach().

You need to begin with all your 27 cubes as a child of the scene.

Let pivot be an Object3D().

Let active be an array containing the 9 cubes you want to rotate. Now make the cubes a child of the pivot:

pivot.rotation.set( 0, 0, 0 );
pivot.updateMatrixWorld();

for ( var i in active ) {

    pivot.attach( active[ i ] );

}

Then, after the rotation, put the cubes back as children of the scene.

pivot.updateMatrixWorld();

for ( var i in active ) {

    scene.attach( active[ i ] );

}

three.js r.115

like image 148
WestLangley Avatar answered Oct 14 '22 07:10

WestLangley