What's the best way to have a Json model automatically rotate within the scene?

Using mouse events, I am able to rotate the ballmesh.

First attempt

var jsonLoader = new THREE.JSONLoader();
jsonLoader.load('models/ball.json', addJsonToScn);

function addJsonToScn(geometry) {
        var ball = new THREE.BufferGeometry().fromGeometry(geometry);
        var mtl = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
        ballmesh = new THREE.Line(ball, mtl);
        scene.add(ballmesh);
    }

document.addEventListener('click', rotateMesh, false);

function rotateMesh() {
    ballmesh.rotation.y += 0.1;
}


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

Upon clicking the window, the mesh will rotate along the y-axis.

This implies that before clicking the window, the mesh is fully loaded into the scene.

However, in order for the mesh to auto-rotate, I made some modifications to the code.

Second attempt

I included

ballmesh.rotation.y += 0.1;

within the animate(); function

var jsonLoader = new THREE.JSONLoader();
jsonLoader.load('models/ball.json', addJsonToScn);

function addJsonToScn(geometry) {
        var ball = new THREE.BufferGeometry().fromGeometry(geometry);
        var mtl = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
        ballmesh = new THREE.Line(ball, mtl);
        scene.add(ballmesh);
    }

document.addEventListener('click', rotateMesh, false);

function rotateMesh() {
    ballmesh.rotation.y += 0.1;
}


function animate() {
    ballmesh.rotation.y += 0.1;
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
}

Unfortunately, an error occurred

TypeError: ballmesh is undefined

It appears that the mesh has not been completely loaded yet.

If I wish for the mesh to auto-rotate, what steps should I take?

Answer №1

The challenge you are facing is not related to three.js but to the event-driven nature of JavaScript. It is crucial to understand the timing of code execution in a real-world scenario.

In this specific case, you are initiating a request to load a model and attaching an "on completion" event to it. However, the event handler will only run after the model has finished loading and processing, even though you define it earlier in your code.

Following the initiation of the request, your main code proceeds to animate the scene. Since the completion event has not yet been triggered (as the model is still loading), you encounter an error due to an undefined variable.

Eventually, once the model is fully loaded, the event handler will set the variable value. Unfortunately, by that point, the animation loop has already encountered issues caused by the undefined variable.

One simple workaround for your situation is to check if the mesh is defined before animating it:

function animate() {
    if ( ballmesh !== undefined ) {
         ballmesh.rotation.y += 0.1;
    }
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
}

Alternatively, you could start your animation loop within the addJsonToScn event handler. Note that this method may be limited to straightforward cases like yours, where you are waiting for a single load event.

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

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Upon refreshing the page, an inline script was not executed due to its violation of the Content Security Policy directive: "script-src 'self'"

When I refresh the page on my production build for all routes except "/", I encounter an error in my Node/React app which results in a blank page being displayed. The error message states: "Refused to execute inline script because it violates the followi ...

Is there a way to launch my JavaScript project locally and have index.html served on an npm server?

I am currently attempting to launch a specific Single Page Application (SPA) project using pure JavaScript. This project consists of a script file and an index.html file. I am trying to run this project on my local machine, but it requires that it be hos ...

default selection in AngularJS select box determined by database ID

Here is the scenario: ... <select ng-model="customer" ng-options="c.name for c in customers"> <option value="">-- choose customer --</option> </select> .... In my controller: $scope.customers = [ {"id":4,"name":"aaaa", ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

Navigate through pages using scrollspy without losing your position when returning

Hey all you web geeks out there, I could really use your help solving a little issue. I've been working with Bootstrap to build a website that utilizes scrollspy for navigating different sections of the page using the navbar. The only way I could sto ...

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

Following the submission of the ajax form, the page is reloading unexpectedly

I need the voting form on index.php to submit without refreshing the page and display results from an external page within index.php. HTML <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script&g ...

Incorporating an element into a nested array

I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one. This is my current array: const ...

Open a web browser and continuously monitor the updates by using the `tail

Currently, I have developed a Python script that continually monitors a logfile for modifications (similar to the tail -f command) and showcases it on a console. I am interested in accessing the Python script's output through a web browser. What tools ...

Only the initial submission is allowed when submitting forms using jQuery $.ajax

Encountering an issue with submitting AJAX forms after following this particular tutorial. The forms are contained within div#upform and upon attempting to submit any of them using $.ajax, only the first one is being submitted. The code snippet in questio ...

Issue with optimizing in Webpack 4

It's past 2am and I find myself going crazy trying to identify an error. The console keeps repeating the message: "Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." I've attempted modifyi ...

What is the best way to save longitude and latitude coordinates in a database using the <input> method?

Learn how to use HTML code <html> <body> <p>Press the button below to receive your coordinates.</p> <button onclick="getLocation()">Get Coordinates</button> <p id="demo"></p> <script> var x = doc ...

Ways to search for and compare items within an array obtained from the results of a loop once the loop has finished executing in JavaScript

I am encountering an issue with my JavaScript code while working on a reminder app in Cordova and using the Katzer notification plugin. My goal is to implement a feature where, if a user tries to add a reminder that already exists, an error is thrown. Conv ...

Fade in and out effect for popups on Leaflet markers

As I delve into developing a map web app using Angular, one challenge I face is incorporating fading popups for markers. I envision these popups fading in and out on their own as per a timer, but I lack the know-how to achieve this: My current code for cr ...

Using Javascript to open a new page and execute a script

I need to be able to launch a new window window.open(url,'_blank'); After that, I want to execute a JavaScript script like this: window.open(url,'_blank').ready("javascript code here"); However, I'm unsure how to accomplish thi ...

Utilize only certain JSON properties within JavaScript

I have access to an array of JSON objects. [ { Id: "1", StartNo: "1", ChipNo: "0", CategoryId: "0", Wave: "0", Club: "", FirstName: "Lotta", LastName: "Svenström", FullName: "Lotta Svenström", ZipCode: "24231" }, {...} ] My goal is to create a new data ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...