Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant remove objects using Three.JS

I'm using Three.JS to make a plane and put some boxes over it I need remove all boxes sometimes. So I'm trying to do it with the following code:

for ( i = 0; i < scene.children.length; i ++ ) {
    var object = scene.children[ i ];
    if ( object != plane && object != camera) {
        scene.remove(object);
    }
}

/This kill each object that is not the plane or the camera ;-)/

It deletes some boxes, but not all of them =( How can I delete all boxes? Greetings, José

like image 882
José Avatar asked Jul 26 '12 21:07

José


2 Answers

You need to go back to front, not front to back, when removing array objects like this.

var obj, i;
for ( i = scene.children.length - 1; i >= 0 ; i -- ) {
    obj = scene.children[ i ];
    if ( obj !== plane && obj !== camera) {
        scene.remove(obj);
    }
}

What is happening is when one removes a node, all the ones after it shift. Let's say you remove scene.children[0]: children[1] will become the new 0, 2 will become 1, etc. When going from 0 to array.length, the for loop has already moved on and is skipping 1 node for every one you delete.

As an additional plus, this should go slightly faster, especially if you have many objects, since scene.children.length is only gotten once, instead of every loop.

like image 74
Crazycatz Avatar answered Nov 15 '22 23:11

Crazycatz


@Crazycatz answer is correct of course but now we are in 2016 and instead of manual iteration we can just call .slice() and iterate over array copy:

scene.children.slice().forEach(obj => scene.remove(obj))

or without ES6 goodies:

scene.children.slice().forEach(function(obj) { scene.remove(obj); })
like image 28
csharpfolk Avatar answered Nov 15 '22 21:11

csharpfolk