[SOLVED] Retain global position and scale of element when reparenting

Yeah that’s a bit tricky. If you are using uniform scale (so if scale.x, scale.y, scale.z are equal) you could do something like this:

var mat = child.getWorldTransform().clone();
var parentMat = parent2.getWorldTransform().clone().invert();
mat.mul2(parentMat, mat);
var pos = mat.getTranslation();
var rot = new pc.Quat().setFromMat4(mat);
var scale = mat.getScale();

child.reparent(parent2);    
        
child.setLocalPosition(pos);
child.setLocalRotation(rot);
child.setLocalScale(scale);

What this does basically is it gets the world transform of the child, transforms it into the new parent’s space and then gets the position, rotation, scale from the transformed matrix and assigns them to the reparented child.

2 Likes