When I add an Object3D to another Object3D ("add" method) the child changes its transform depending on parent's one.
Is there a way to keep position/rotation/scale of the child after adding it to a parent?
Fiddle: https://jsfiddle.net/pqfzd8a2/1/
mesh = new THREE.Mesh(geometry, material);
mesh.position.y = 25;
var mesh2 = mesh.clone();
mesh2.position.y = 80;
var mesh3 = mesh2.clone();
mesh.rotation.z = Math.PI*0.25;
scene.add(mesh);
mesh.add(mesh2);
scene.add(mesh3);
What was done?
- mesh is rotated.
- mesh2 and mesh3 are clones of each other with same position.
- mesh2 is added to mesh, while mesh3 was added to scene.
The difference between mesh2 and mesh3 is that they were added (parented) to different parents (to mesh and directly to the scene, correspondingly). Before being added (parented) to something, they were in same position. The point is to keep the object where it was before being added (parented).
Expected result: mesh2 and mesh3 should be in the same positions.
Actual result: mesh2 changes position/rotation/scale after being added.
How to make objects keep their global transform after being parented?
Well that is the defined behaviour and at least the reason why those hierarchical structures exist. If you do not want to apply the parent's transform on the child, there is no reason to parent those items.
With this approach it is much easier to handle complex Objects, which are composed of smaller objects, like a car with wheels. Instead of moving the car and then each wheel, one makes the wheels childs of the car and they will move/rotate/scale with it all the time. That is how the transformation of the parent is »inherited« by all its children. So their transform is relative their respective parent. Like the moon rotates around the earth, which rotated around the sun, which rotates around whetever…
If you really need to cancel out the parents transform within a child, then you need to apply the inverse of parents transform to the child's transform, but as I said, that does not make much sense, because you just do not need to parent them and your done.