Is there a way to ungroup an object in a group but remain in the scene?
Sounds like a job for SceneUtils.detach().
2 Likes
solved, thanks.
// we pass to the function the child object of another object as a parameter.
function unGrupsinBorrar (ModelSelect) {
// we get the Id
var elId=ModelSelect.id;
// declare the object in a variable
var objetUngrup=scene.getObjectById(elId);
// we get the position
var laPosicion=(scene.getObjectById(elId)).getWorldPosition();
// we get the rotation
var laRotacion=(scene.getObjectById(elId)).getWorldRotation();
// we remove the object from the scene - it is not deleted because it is declared in the variable--
scene.remove(scene.getObjectById(elId));
// We add the object to the scene - it appears in the position (0,0,0) and rotation (0,0,0)
scene.add(objetUngrup);
// We recover the position
objetUngrup.position.copy(laPosicion);
// We recover the rotation
objetUngrup.rotation.copy(laRotacion);
// The object is now inserted as a child of the scene, with the same ID it had
}
You should consider the following to improve the performance of your code:
- Every time you call
.getWorldPosition()
and.getWorldRotation()
, you create for each call a new object ofVector3
. To avoid this, apply a result object as a parameter.
var laPosicion = new THREE.Vector3();
function unGrupsinBorrar (ModelSelect) {
var elId=ModelSelect.id;
var objetUngrup=scene.getObjectById(elId); // only call this once and reuse objetUngrup
objetUngrup.getWorldPosition( laPosicion );
// ...
- Also consider to work with
matrixWorld
directly. It simplifies your code and you don’t miss any transformations like scaling. Check out the source code ofSceneUtils.detach()
for more information.
1 Like
I needed to ungroup recursively and made this.
function flattenGroup(group, recursive) { // group can be the entire scene
group.updateMatrixWorld();
var again;
do {
again = false;
group.children.slice().reverse().forEach(function(parent){
parent.children.slice().reverse().forEach(function(child){
again = true;
parent.remove( child );
child.applyMatrix( parent.matrix );
group.add( child );
});
});
} while (again && recursive);
group.children.slice().reverse().forEach(function(child){
if (child.type == 'Group'){
if(child.children.length == 0){
group.remove( child );
} else{
console.log("group still has children")
}
}
});
}