Using three.js, and adapting instructions from West Langley's post provided here: Three.js: Adding and Removing Children of Rotated Objects, I set up a WebGL scene to which five cube meshes are added. Initially, all objects are children of the scene, then, I attach them to the fifth "parentCube" cube and translate it 100 units along the Y-Axis thereby translating the other four cubes and subsequently detach them.
After that, I want to independently translate the "parentCube" cube (previously the parent of the four cubes) back to the origin, however, when I perform that translation, the other four cube meshes also translate with the former parent cube mesh, even when I detached them.
This may be a very basic question, but how can I independently translate "parentCube" without affecting the position of the other cubes considering all of the above details? Where am I going wrong with the detachment? Any help would be appreciated. Thank you :)
Here's the code sample which I use to perform all of the above:
//Create parentCube mesh
var parentCube = new THREE.Mesh(new THREE.CubeGeometry(100, 100, 100, 10, 10, 10), new THREE.MeshBasicMaterial({ color: 0xa1ff11, wireframe: true }));
scene.add(parentCube);
//...create materials for the child cubes....
//create child cube mesh
for(var i = 0; i < 4; i++)
cubeMesh[i] = new THREE.Mesh(new THREE.CubeGeometry(100, 100, 100, 30, 30, 30), materials[i]);
//--> Set child cube world positions before the attachment to parentCube mesh
cubeMesh[0].position.set((100 / 2),(100 / 2),(100 / 2));
cubeMesh[1].position.set(-(100 / 2),(100 / 2),(100 / 2));
cubeMesh[2].position.set(-(100 / 2),-(100 / 2),(100 / 2));
cubeMesh[3].position.set((100 / 2),-(100 / 2),(100 / 2));
//Add child cubes to the scene
for(var i = 0; i < cubeMesh.length; i++)
scene.add(cubeMesh[i]);
//attach child cubeMesh[i] to parentCube mesh
for(var i = 0; i < 4; i++)
THREE.SceneUtils.attach(cubeMesh[i], scene, parentCube);
//--> Set positions of child elements after attachment to parentCube
cubeMesh[0].position.set((100 / 2),(100 / 2),(100 / 2));
cubeMesh[1].position.set(-(100 / 2),(100 / 2),(100 / 2));
cubeMesh[2].position.set(-(100 / 2),(100 / 2),-(100 / 2));
cubeMesh[3].position.set((100 / 2),(100 / 2),-(100 / 2));
//translate parentCube
parentCube.position.set(0,150,0);
parentCube.updateMatrixWorld();
//Attempt to detach child objects from parentCube
//And make them children of the scene
for(var i = 0; i < 4; i++)
{
cubeMesh[i].updateMatrixWorld();
THREE.SceneUtils.detach(cubeMesh[i], parentCube, scene);
}
//Attempt to translate parentCube back to origin
parentCube.position.set(0,0,0);
}