在three.js中使用相同的渲染器在两个场景之间切换

时间:2017-05-04 18:23:57

标签: javascript three.js

我一直试图找到一种能够在three.js中的两个场景之间切换的方法。我知道可以使用sceneLoader / exportScene组合加载场景。

代码来自josdirksen/learning-threejs - loading a scene

var controls = new function () {
        this.exportScene = function () {
            var exporter = new THREE.SceneExporter();
            var sceneJson = JSON.stringify(exporter.parse(scene));
            localStorage.setItem('scene', sceneJson);
        };
        this.clearScene = function () {
            scene = new THREE.Scene();
        };
        this.importScene = function () {
            var json = (localStorage.getItem('scene'));
            var sceneLoader = new THREE.SceneLoader();
            sceneLoader.parse(JSON.parse(json), function (e) {
                scene = e.scene;
            }, '.');
        }
    };

根据我对上述代码的理解,您需要首先加载场景,然后才能将其提取并保存到本地存储,然后再将其放回场景中。我也知道现在不推荐使用SceneLoader。

对于我的senario,我希望有一个初始场景加载,然后点击'scene2'按钮,然后我想只显示scene2,如果我点击'scene1'按钮,只返回看scene1(见下面的小提琴)。

A Basic Example setup

我不知道从哪里开始,所以任何指针建议或建议都会有所帮助。

2 个答案:

答案 0 :(得分:4)

如果你只需要切换到新场景,那么为什么不要有两个场景对象和一个主场景。请尝试以下代码

/* Buttons to handle scene switch */
$("#scene2").click(function() {
  scene = scene2
})
$("#scene1").click(function() {
  scene = scene1
})

function init() {
  ....

  /* I dont think you need to add camera to scene for viewing perpose. By doing this, essentially you are adding camera object to scene, and you won't be able to see it because scene is rendered using this camera and camera eye is at same location
  */
  scene1 = new THREE.Scene();
  // Build scene1
  //  scene1.add(camera);


  scene2 = new THREE.Scene();
  // Build scene2    

  // Choosing default scene as scene1
  scene = scene1;
}
function render() {
  // Try some checking to update what is necessary

  renderer.render(scene, camera);

}

更新了jsfiddle

答案 1 :(得分:1)

您可以通过删除当前场景scene.remove(mesh);重绘画布并添加创建新的网格添加到场景

演示 http://jsfiddle.net/sumitridhal/x8t801f5/4/

您可以使用dat.GUI库添加自定义控件。

<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.4/dat.gui.js"></script>

//

 var controls = new function() {
    // we need the first child, since it's a multimaterial
    this.radius = 10;
    this.detail = 0;
    this.type = 'Icosahedron';

    this.redraw = function() {
 // remove the old plane
      scene.remove(mesh);
      // create a new one
 // add it to the scene.
      scene.add(mesh);
   }
});
 var gui = new dat.GUI();
  gui.add(controls, 'radius', 0, 40).step(1).onChange(controls.redraw);
  gui.add(controls, 'detail', 0, 3).step(1).onChange(controls.redraw);
  gui.add(controls, 'type', ['Icosahedron', 'Tetrahedron', 'Octahedron', 'Custom']).onChange(controls.redraw);

演示 http://codepen.io/sumitridhal/pen/NjbGpB