Search code examples
canvasthree.jsscene

scene inside a scene with three js


I am working on creating a snowman with its stomach being a snow globe. I was wondering if there was a way to create a scene within a scene. Basically when I scroll into his belly I want to load a different scene. Is this possible. Here is my basic code on what I have so far.

<!DOCTYPE html>
<html>


<head>
    <title></title>
      </head>
      <body>
        <script src="three.js"></script>
        <script src="TrackballControls.js"></script>
        <script>

      var camera, controls, scene, renderer;

      init();
      animate();

      function init() {
        camera = new THREE.PerspectiveCamera(75,window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.z = 10;

        controls = new THREE.TrackballControls( camera );
        controls.addEventListener("change", render);

        scene = new THREE.Scene();

        var geometry = new THREE.SphereGeometry(4,32,32);
        var material = new THREE.MeshBasicMaterial( { color: 0xcacec6 });
        var middleSphere = new THREE.Mesh( geometry, material );
        scene.add( middleSphere );
        middleSphere.position.y = -0.5;

        renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild( renderer.domElement );
      }

      function ani`enter code here`mate() {
        requestAnimationFrame( animate );
        controls.update();
      }

      function render() {
        renderer.render( scene, camera );
      }


    </script>


  </body>
</html>

Solution

  • I would suggest making an additional scene, possibly with its own camera, and load the objects you want inside it.

    Then have some kind of check in your render() or animate().

    pseudo code

    make scene1 with objects and camera1
    make scene2 with objects and camera2
    make empty scene called currentScene
    set currentScene to scene1
    set currentCamera to camera1
    create sceneIndex or a bool to check which scene and camera is currently used
    
    //in render() or animate()
    if( sceneIndex == 1 && its position inside snowman)
    currentScene = scene2, currentCamera = camera2 and update sceneIndex
    
    else if(sceneIndex == 2 && its cameraposition outside snowman)
    currentScene = scene1, currentCamera = camera1 and update sceneIndex
    
    //render
    renderer.render(currentScene,currentCamera)
    

    Hope it helps