如何从场景中删除网格的子集?

时间:2019-05-09 20:08:20

标签: javascript three.js

当我创建多个具有相同名称的网格物体时,如果要从场景中删除它们,就无法全部选中它们。

我尝试遍历该函数无济于事。

event.preventDefault();

scene.traverse(function(child) {
   if (child.name === "blueTiles") {
      var remove_object = scene.getObjectByName( "blueTiles", true );
      scene.remove(remove_object); 
   }
});

var surroundMaterial = new THREE.MeshBasicMaterial({ color: 0x154995, side: THREE.DoubleSide, transparent: true, opacity: 0.8 });
surroundingCubes = new THREE.Mesh( geometry, surroundMaterial );
scene.add( surroundingCubes );
surroundingCubes.name = "blueTiles";
surroundingCubes.position.set(selectedObject.position.x - 1, 0.11, selectedObject.position.z);

var surroundMaterial = new THREE.MeshBasicMaterial({ color: 0x154995, side: THREE.DoubleSide, transparent: true, opacity: 0.8 });
surroundingCubes = new THREE.Mesh( geometry, surroundMaterial );
scene.add( surroundingCubes );
surroundingCubes.name = "blueTiles";
surroundingCubes.position.set(selectedObject.position.x + 1, 0.11, selectedObject.position.z);
surroundingCubes.rotation.x = Math.PI / 2;

我应该只能删除所有名称为blueTiles的对象

EDIT我从名称切换到了网上论坛,这确实产生了奇迹 下方解决方案

function onDocumentMouseDown(event) {

for (var i = group.children.length - 1; i >= 0; i--) {
    group.remove(group.children[i]);
}

var surroundingMaterial = new THREE.MeshBasicMaterial({ color: 0x154995, side: THREE.DoubleSide, transparent: true, opacity: 0.8 });
var geometry = new THREE.PlaneGeometry(1, 1, 1, 1);

if ( selectedObject.position.x - 1 >= 0) {
    surroundingCube = new THREE.Mesh( geometry, surroundingMaterial );
    surroundingCube.position.set(selectedObject.position.x - 1, 0.11, selectedObject.position.z);
    surroundingCube.rotation.x = Math.PI / 2;
    group.add(surroundingCube);

}

if ( selectedObject.position.x + 1 <= 9) {
    surroundingCube = new THREE.Mesh( geometry, surroundingMaterial );
    surroundingCube.position.set(selectedObject.position.x + 1, 0.11, selectedObject.position.z);
    surroundingCube.rotation.x = Math.PI / 2;
    group.add(surroundingCube);

}

scene.add( group );
}

2 个答案:

答案 0 :(得分:1)

getObjectByName仅调用getObjectByProperty(使用name属性),该操作仅返回找到的第一个对象。
您实际上只需要遍历场景/ object3d的children,检查其名称,然后删除。
如果您知道要删除的所有文件都位于顶层,这很简单。
像...。(未测试)

for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  if (scene.children[i].name === 'blueTiles') {
    scene.remove(scene.children[i]);
  }
}

如果您还想在较低级别进行检查,则可能需要某种递归。

编辑...
再次查看您的问题后,并记住有一个遍历功能

您似乎已经遍历了场景并可以访问孩子。
我认为您只需要更改函数(根本不调用getObjectByName)。

scene.traverse(function(child) {
   if (child.name === "blueTiles") {
      scene.remove(child); 
   }
});

答案 1 :(得分:1)

您可以尝试使用THREE.group类对网格进行分组。

一个非常基本的用法是:

 var pc_constraints = {
    optional: [{ 'DtlsSrtpKeyAgreement': true }]
  };