首页 > 解决方案 > 从三个 JS 的场景中删除组类型 GLTF 对象

问题描述

我正在尝试从场景中移除一组对象,scene.remove(group)但没有成功。

这是我的装载机:

GLTFloader.load( src+'.gltf', function ( gltf ) {
                gltf.scene.traverse( function ( child ) {
                    if(child.type === "Group")
                    {
                        newObject = true;
                        GLTFobjects.push(child);
                    }
                    if ( child.isMesh ) {
                        child.receiveShadow = true;
                        child.castShadow = true;
                        child.material.transparent = true;
                        child.material.opacity = 0.7;
                    }
                } );
                scene.add( gltf.scene );

            },function ( xhr ) {

                console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

            },
            // called when loading has errors
            function ( error ) {

                console.log( 'An error happened' );
                console.log(error);

            }
        );

GLTFobjects是包含我所有对象的全局数组。

GLTFobjects 的每个成员都是组类型,假设这个数组的第一个元素应该被删除。

我尝试了以下方法:

scene.remove(GLTFobjects[0])

和:

GLTFobjects.children.forEach(function (value,index) {
                    scene.remove(value);
                });

甚至:

GLTFobjects[0].traverse(function (e) {
                        scene.remove(e);
                    });

没有任何效果。

如何从场景中删除组对象?

注意: GLTFobjects[0]看起来像这样(如果有帮助的话):

{…}​castShadow: false​children: Array(7) [ {…}, {…}, {…}, … ]​frustumCulled: true​id: 24​layers: Object { mask: 1 }​matrix: Object { elements: (16) […] }​matrixAutoUpdate: true​matrixWorld: Object { elements: (16) […] }​matrixWorldNeedsUpdate: false​modelViewMatrix: Object { elements: (16) […] }​name: "House3"​normalMatrix: Object { elements: (9) […] }​parent: Object { uuid: "E6BE42B7-C7D3-4617-83E5-83EACD0948B6", name: "Scene", type: "Scene", … }​position: Object { x: 0, y: 1.1222255229949951, z: -16.519949752598595 }​quaternion: Object { _x: 0, _y: 0, _z: 0, … }​receiveShadow: false​renderOrder: 0​rotation: Object { _x: 0, _y: 0, _z: 0, … }​scale: Object { x: 1, y: 1, z: 1 }​type: "Group"​up: Object { x: 0, y: 1, z: 0 }​userData: Object {  }​uuid: "9F7508DD-E1C2-481D-AF49-57EE3973C27F"​visible: true​<prototype>: Object { constructor: Group(), isGroup: true } 

标签: javascriptthree.js

解决方案


gltf.scene被添加到scene而不是您的GLTFobjects组中。

如果您添加了GLTFobjects,您可以简单地执行以下操作:

GLTFobjects.remove(GLTFobjects.getObjectByName("cube"));

或者

GLTFobjects.remove(GLTFobjects.children[0]);


推荐阅读