Changing between two different scenes by utilizing the same renderer in three.js

I have been experimenting with ways to toggle between two scenes in three.js. I know that one option is to load a scene using sceneLoader and exportScene together.

Code extracted from 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;
            }, '.');
        }
    };

As per my understanding of the provided code, it seems necessary to have the scene loaded before extracting and saving it to local storage for later reinsertion. It's important to note that SceneLoader is deprecated.

In my specific case, I aim to load an initial scene and then switch to display 'scene2' upon clicking a button named 'scene2'. Similarly, another button 'scene1' should revert back to displaying the first scene only (refer to the fiddle link below).

A Basic Example setup

I'm seeking guidance on how to approach this task, so any tips or suggestions would be greatly appreciated.

Answer №1

If you're looking to simply transition to a new scene, why not consider having two separate scene objects within one main scene? Here's a sample code snippet to help get you started:

/* Functions for handling scene transitions */
$("#scene2").click(function() {
  scene = scene2
})
$("#scene1").click(function() {
  scene = scene1
})

function init() {
  ....

  /* It may be unnecessary to add the camera to the scene just for viewing purposes. By doing so, you essentially add the camera object to the scene but won't actually see it as the scene is rendered using this camera from the same location. */
  scene1 = new THREE.Scene();
  // Build scene1
  // scene1.add(camera);

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

  // Setting default scene to be scene1
  scene = scene1;
}
function render() {
  // Implement logic to update elements as needed

  renderer.render(scene, camera);
}

Check out the updated jsfiddle for reference.

Answer №2

To refresh the canvas, simply remove the current scene with scene.remove(mesh); and then add a new mesh to the scene.

See it in action: http://jsfiddle.net/sumitridhal/x8t801f5/4/

You can customize controls using the dat.GUI library.

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

//

 var controls = new function() {
    this.radius = 10;
    this.detail = 0;
    this.type = 'Icosahedron';

    this.redraw = function() {
        scene.remove(mesh);
        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);

Check out the live demo: http://codepen.io/sumitridhal/pen/NjbGpB

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The method 'getAjaxResponse' is not available for Object #<AbstractAjaxReq>

Looking to incorporate OOP best practices into my javascript code. Currently, I have an abstractAjaxRequest with child classes defining the getAjaxResponse function. However, I am encountering an error on the line self.getAjaxResponse(). Any ideas on how ...

Obtain data from a single module and incorporate it into a different one

In my Angular 2 application, I am dealing with two component files - home.ts and folder-selector.ts. Within the folder-selector.ts file, there is a variable named pathToNode. I am trying to figure out how to access this value from within the home.ts file ...

Using JavaScript to determine the time it will take to download something

Hi everyone, I'm a beginner in javascript and I am currently working on finding the download time of a file. I have calculated the size of the file and divided it by the current time, but unfortunately, I am not getting the correct result. This is th ...

Issue with ng-model causing incorrect variable binding

My issue lies with a variable that I have connected to a select input through the use of ng-model. Strangely, the variable seems to not update with the correct data and retains the value assigned to it during initialization. I have a similar setup elsewhe ...

What are the differences between three.js domElement and the documentElement?

When referring to the THREE JS documentation, it suggests using domElement in this manner: document.body.appendChild(renderer.domElement); I'm wondering if there is a distinction between this approach and utilizing documentElement instead. This is c ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

Sequelize is incorrectly pointing to an invalid foreign key

There are two tables in my database, namely Transaction and Transaction Details. The recordId serves as a foreign key in the Transaction Details table. My goal is to query a specific Transaction based on its recordId and include all associated Transaction ...

A guide on incorporating oAuth 2.0 into Tizen

Currently, I am in the process of incorporating Google authentication using oAuth 2.0 in Tizen. I am following the guidelines provided here. Despite successfully obtaining the user code as instructed in the link, I keep receiving an invalid request error w ...

What is the method to alter the color of an SVG source within an image tag?

I am currently working on a component that involves changing the color of an SVG icon from black to white when a color prop is given. export class CategoryIconComponent extends React.Component { static displayName = 'CategoryIcon'; state = ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

Why does this particular user continue to encounter validation errors in ASP.NET?

While most of us successfully submitted the request form for server decommission, one particular individual encountered an issue. They were unable to submit the form due to a pop-up alert stating "Invalid User Data, return to form." Despite verifying their ...

Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try. So far, here's what I've done: Inserted code into themes functions.php function test_my_script() { wp_register_script( 'custom-s ...

Creating an XML response to generate an HTML dropdown menu in PHP

My onChange function in javascript calls a PHP file to fetch UPS rates and update an HTML dropdown list. Everything was working fine until I needed to add an item to the options list based on a comparison. Javascript: function fetch_UPS(el){ var zip = ...

Code for switching between accordion panels with a simple button press

I took some code snippets from a website and developed a shopping cart accordion module. The complete code is available on my CodePen profile, you can access it through this link: http://codepen.io/applecool/pen/YXaJLa <div class="summary"> <but ...

How can PHP be used to create Javascript?

Is there a specific library or tool tailor-made for PHP programmers to seamlessly transition their logic into Javascript? For example: $document = new Document($html); $myFoo = $document->getElementById("foo"); $myFoo->value = "Hello World"; Which ...

The complete guide to effectively concealing double arrows within a Bootstrap 4 custom-select component

If you're looking to hide the double arrow on the right of the bootstrap 4 custom-select field, there have been solutions provided here. However, even after implementing those changes, the text on the right-hand side still gets obscured by the opaque ...

Canceling a window in JSP and navigating back to the previous page using JavaScript

Here is my Java class controller: public class Controller extends HttpServlet { private Chooser chooser = Chooser.INSTANCE; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOExcep ...

Transforming retrieved data into an array using Node.js

Got some data from a URL that looks like this: data=%5B1%2C2%2C3%2C4%2C0%5D which when decoded is [1,2,3,4,0]. Used the snippet below to parse the data: var queryObj = querystring.parse( theUrl.query ); Seems like it's not an array. How can I con ...