Three.js: Proper way to add and remove child objects using THREE.SceneUtils.attach/detach functions

This is an old post but the sake of search engines here are my thoughts about this

Looking at the code for THREE.SceneUtils.attach() it appears to me that the code assumes the object that you want to attach is parented to the scene object. This makes it problematic to work with when your objects are actually nested further down in the scene graph. To address this problem I wrote this function

function reparentObject3D(subject, newParent)
{
    subject.matrix.copy(subject.matrixWorld);
    subject.applyMatrix(new THREE.Matrix4().getInverse(newParent.matrixWorld));
    newParent.add(subject);
}

This allows you to reparent an object from any level of the scene graph to any other level in the scene graph. This dispenses with the need to "Detach" objects. You just reparent them to the scene if thats what you need

Tags:

3D

Three.Js