Understanding Three.js Fundamentals: Resolving GLTFLoader Animation and Variable Not Found Issues

My understanding of JS is very basic. After exploring the three.js docs on Loading 3D models, I managed to successfully render a 3D object and center it:

const loader = new GLTFLoader();

loader.load( 'Duck.gltf', function ( duck ) {
    
    const model = duck.scene
    const box = new THREE.Box3().setFromObject( model );
    const center = new THREE.Vector3();
    box.getCenter( center );
    model.position.sub( center ); // center the model
    scene.add( model );

}, undefined, function ( error ) {

    console.error( error );

} );

Now, I am eager to animate it starting with a simple rotation:

/**
 * Animate
 */

const clock = new THREE.Clock()

const tick = () =>
{

    const elapsedTime = clock.getElapsedTime()

    // Update objects
    model.rotation.y = .5 * elapsedTime

    // Update Orbital Controls
    // controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

However, I encountered an issue as the console returns:

ReferenceError: Can't find variable: model

Answer №1

Always remember to declare model variables outside of the functional scope for optimal performance!

const loader = new GLTFLoader();
let model, box, center;

loader.load('Duck.gltf', function (duck) {
    
    model = duck.scene
    box = new THREE.Box3().setFromObject(model);
    center = new THREE.Vector3();
    box.getCenter(center);
    model.position.sub(center); // center the model
    scene.add(model);

}, undefined, function(error) {
    console.error(error);
});

Fingers crossed that everything runs smoothly!

Updated

Following advice from @prisoner849 in the comments section

const clock = new THREE.Clock()
const tick = () => {
    const elapsedTime = clock.getElapsedTime()
    // Update objects
    if (model) {
       model.rotation.y = .5 * elapsedTime
    }
    // Update Orbital Controls
    // controls.update()
    // Render
    renderer.render(scene, camera)
    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

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 sets asyncData apart from methods in Nuxt.js?

I am currently utilizing asyncData to fetch data from an API, however it is restricted to pages and cannot be used in components. On the other hand, methods can be used in both pages and components. As these two methods function similarly, I am consider ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...

Animate the transition of the previous element moving downward while simultaneously introducing a new element at the top

I currently have a hidden element called "new element" that is controlled by v-if. My goal is to create a button labeled "display" that, upon clicking, will reveal the new element on top after sliding down an old element. How can I achieve this using CSS ...

Utilizing jQuery for AJAX requests on a timed loop

I'm puzzled by a situation involving an AJAX call within an interval. It seems that the code doesn't work as expected, and I'm wondering why. Initially, I had this code snippet which wasn't functioning properly: setInterval($.ajax({ ...

Unable to deploy Azure App Service due to difficulties installing node modules

My Azure Node.js App Service was created using a tutorial and further customization. The app is contained within one file: var http = require("http"); //var mongoClient = require("mongodb").MongoClient; // !!!THIS LINE!!! var server = http.createServer(f ...

Angular ng-repeat not recognizing nested ng-if conditions

Hey there, I'm trying to make sure that only the option corresponding to the code used by the client to log in is displayed. The HTML should show the option that matches the client's login code. View: <div class=""> <select id="custo ...

Encountering a "Element is not defined" error in Nuxt when trying to render Editor.js and receiving

I've been working on creating an editor using Editor.js within my Nuxt project, but it seems like the editor isn't initializing properly when I render the page. import EditorJS from '@editorjs/editorjs'; interface IEditor { editor: E ...

What is the best way to utilize props and mounted() in NuxtJS together?

I'm a beginner with NuxtJS and I'm looking to implement window.addEventListener on a specific component within my page. However, I also need to ensure that the event is removed when the page changes. In React, I would typically approach this as ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

Capture a screenshot of an embedded object and include it in an email using the mailto function

Is there a way to capture a screenshot of a flash object on a webpage and then send it via email using a mailto: form submission to a designated address? I have attempted to use different JavaScript techniques, but none seem to be successful. Appreciate a ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

How can we display a different navbar based on whether the user is logged in or not?

Can anyone share the most effective methods for displaying a different navbar based on whether or not a user is logged in? I have considered a few approaches: One option might involve creating two separate navbars in the HTML file and using CSS to tog ...

.submit fails to function when the bound object has been updated via an ajax call

I managed to implement an AJAX commenting system where, upon clicking the Post Comment button, an ajax call is made instead of submitting the form traditionally. Everything was working smoothly until I tried refreshing the page with the comment submit butt ...

When attempting to install React Native on a Mac using the "npx react-native init MyTestApp" command, the

PROBLEM I am encountering difficulties while attempting to install and execute the react native todo command - npx react-native init MyTestApp on my MacBook Pro. The specific challenges I am facing are: The detailed github issue can be found here: here ...

Trouble with escape sequences in regular expressions within jQuery Terminal for JavaScript

I'm experimenting with special character functionality in jQuery terminal. While I was successful in implementing the backspace functionality, I encountered an issue when trying to execute the escape functionality. Below is the code snippet I used: ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

Hovering over the top menu items in AngularJS will reveal dropdown submenus that will remain visible even when moving the cursor

I am facing an issue where my top menu has links that display a dropdown of additional menu items upon hovering. I have attempted to use onmouseover and onmouseleave events to control the visibility of the sub menu. However, I have encountered a problem ...

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...