javascript 无法使用 Three.JS 删除对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11678497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cant remove objects using Three.JS
提问by José
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:
我正在使用 Three.JS 制作一架飞机并在上面放一些盒子我有时需要移除所有盒子。所以我正在尝试使用以下代码来做到这一点:
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é
它删除了一些框,但不是全部 =( 我怎样才能删除所有框?问候,何塞
回答by Crazycatz
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.
发生的事情是当一个节点删除时,它之后的所有节点都移动了。假设您删除了 scene.children[0]:children[1] 将成为新的 0,2 将成为 1,等等。当从 0 到 array.length 时,for 循环已经移动并跳过 1 个节点 for你删除的每一个。
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.
作为一个额外的好处,这应该会稍微快一点,特别是如果你有很多对象,因为 scene.children.length 只得到一次,而不是每次循环。
回答by csharpfolk
@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:
@Crazycatz 答案当然是正确的,但现在我们在 2016 年,而不是手动迭代,我们可以调用.slice()
并迭代数组副本:
scene.children.slice().forEach(obj => scene.remove(obj))
or without ES6 goodies:
或者没有 ES6 好东西:
scene.children.slice().forEach(function(obj) { scene.remove(obj); })
回答by Sebastian Sachtleben
You should use !== instead of != (its a bit faster). Did you tried to step through your loop and check scene children after that? Maybe you added some boxes to the plane as childs which will not be deleted by this loop.
你应该使用 !== 而不是 != (它有点快)。你有没有尝试过你的循环并在那之后检查场景孩子?也许你在飞机上添加了一些盒子作为孩子,这些盒子不会被这个循环删除。