如何使用 Three.js 基于按钮点击替换场景中的对象?

Dum*_*mbo 1 three.js

删除场景上的旧对象并使场景可用于添加新对象

我开发了一个应用程序,该应用程序将 3D 自定义对象添加到网格中,然后将网格添加到场景中。我的页面上也有一个 Button,当我单击它时,应该从网格中删除已经创建的对象,网格是场景的子项,并且场景应该准备好添加新对象,就像第一次一样。我的意思是,如果可能的话,可以移除整个网格,并且应该将具有新对象集的新网格添加到场景中。

function xyz() // Button click function
{
  // should remove the objects in the scene if exists and make scene available to add 
  // new objects
  for ex: scene.remove(mesh)....???
  // Also needed to clear the renderer??
   .
   .
   .
   do something
 }
 function init()
 {
   // adds the objects to the scene and instantiate renderer
    mesh = New THREE.Mesh({// some material});
    cube = new THREE.CubeGeometry(1,1,1);
    object = new THREE.Mesh(cube,material);
    mesh.add(object);
    scene.add(mesh);
 }
 function animate()
 {
        requestAnimationFrame(animate);
        render();
 }
 function render()
 {
   renderer.render(scene, camera);
 }
Run Code Online (Sandbox Code Playgroud)

Dan*_*son 5

我根据您包含的代码段对您的代码做出了很多假设,因此可以尝试:

function xyz() {

    var l = scene.children.length
        ;

    //remove everything
    while (l--) {

        if(scene.children[l] instanceof THREE.Camera) continue; //leave camera in the scene

        scene.remove(scene.children[l]);

    }

    //reinitialise your stuff
    init();

}
Run Code Online (Sandbox Code Playgroud)