Exploring sections of a GLTF import within the primary rendering loop (apologies for any beginner questions)

As a Unity developer venturing into learning Three.js, I've come across a seemingly simple yet frustrating issue.

My goal is to import and animate a 3D logo consisting of four separate meshes (elem1 to elem4) in my Three.js application. After exporting the logo as an FBX and converting it to GLTF using an online tool, I managed to import it successfully, resize it, and even change its material without any problems.

However, my challenge lies in referencing the entire object and its individual elements to animate them within my "animate" function (the main rendering loop). The only solution I found was creating a secondary "animate" function within the loader callback, which felt awkward. I couldn't figure out how to reference them in the main scope of my application.

Upon dumping my GLTF import, I obtained this hierarchy (referred to as "nodes"):

AuxScene [Scene]
    *no-name* [Object3D]
        elem1 [Mesh]
        elem2 [Mesh]
        elem3 [Mesh]
        elem4 [Mesh]

Below is a stripped-down version of my code:

'use strict';

// Code omitted for brevity

renderer.render( scene, camera );
requestAnimationFrame( animate );

function animate( time ) {
  /*
    This is where I would like to access my logo (both as a whole and separately).
    However, root.rotation or elem1.rotation cannot be accessed here, resulting in an error.
  */  
  renderer.render( scene, camera );
  requestAnimationFrame( animate );
}

// Object Dumping function omitted for brevity

Thank you for any assistance.

Answer №1

The issue arises when attempting to access root before assigning a value (the glTF model) to it. It's important to note that GLTFLoader.load() operates asynchronously. This means that the callback function onLoad(), which sets root, is not immediately executed but with some delay.

To address this problem, there are a few solutions available. One approach is to check in the animation loop if root is not undefined. Here's an example of how it can be implemented:

function animate( time ) {
    requestAnimationFrame( animate );

    if ( root ) {

        // perform actions with root

    }

    renderer.render( scene, camera );

}

Alternatively, you can initiate the animation only after the completion of onLoad(). In this scenario, the code would resemble the following:

'use strict';

// CODE SNIPPET CONTINUES...

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 transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript? I have recently started using rails routes within my application, even in js. The current code I am using is: # app/assets/javascript/verifying_link.js $.ajax({ url: "/verify_link/ ...

"Request sent through Ajax can only be accepted by Localhost and specified IPs

Having an issue with my ajax post request. I want to post to a specific URL, but I also want it to accept both "localhost" and the IP address in the browser. If I set it up like this: $.ajax({ url: 'http://192.168.9.30/test/suma.php&ap ...

Create JSX code for rendering components outside of the main component

As someone who is diving into the world of React, I am currently on lecture 23 out of 247 on Udemy where I am learning about states and events. However, one particular question has been lingering in my mind without a definitive answer. Our company has mad ...

Identifying Internet Explorer's tracking protection through feature detection in JavaScript

It seems that Soundcloud does not offer support for browsers older than IE11, possibly due to tracking protection in IE9 and IE10. Is there a simple method using javascript to detect if tracking protection is enabled? I want to filter out all users with ...

How can we show pictures when a user clicks?

After creating a model for displaying images in a modal when clicked by the user, I encountered an issue. Whenever I try to access the images from the gallery within the modal content, it only displays a blank popup. I want the pictures from the image gall ...

es-lint is issuing a warning about the presence of multiple modules within the node_modules directory that have names differing only in their casing

After reviewing all my import statements, I found that everything looks correct. The only unusual import I have is react-bootstrap, which I import as: import { Jumbotron, Button } from 'react-bootstrap'; I'm using the Jumbotron and Button ...

Is it possible to use speech recognition on browsers besides Chrome?

Is there a way to utilize a microphone with JavaScript or HTML5 without relying on Flash technology? I was able to achieve this in Chrome by using webkit-speech, but I am looking for solutions that will work in other browsers as well. Any suggestions wou ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Instructions on how to create a horizontal scrolling div using the mouse scroll wheel

I need help with scrolling a div horizontally using the mouse scroll button. My div does not have a vertical scroll and I would like users to be able to scroll horizontally. Can anyone provide guidance on how to achieve this? ...

Failed to connect to Wordpress REST API when calling it from a NextJS server due to ECONNREFUSED error

I am currently working on a basic example that involves fetching a list of page slugs from the WordPress REST API, but I am encountering some unexpected behavior. My getPageList() function is an asynchronous function that makes a simple call to the WP API ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Creating multiple synchronous loops within a Vue component using JavaScript

I'm dealing with a JavaScript loop that processes data from an Excel file. The loop loops through the results and retrieves a list of PMIDs. If the PMIDList has more than 200 items, it needs to be split into segments of 200 for processing due to restr ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

Utilizing Node.js and Express.js to Parse HTML Form Inputs

Having trouble extracting input from an HTML form and utilizing it in Node.js. Here is the HTML form being used: <form action="/myform" method="POST"> <input type="text" name="mytext" required / ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

The attempt to generate a .zip file using Node.js with Egg framework was unsuccessful

I developed a Node.js service using Egg framework to send a local .zip file (compressed directory) to the browser, but encountered an issue. Below is the code snippet: Egg.js // Code for zipping files async download() { const ctx = this.ctx; co ...

How can I render just one event instead of all events when using the eventRender callback function?

I am currently working on adding an event to my calendar using a JSON format with specific attributes like id and start time. Here is what I have tried so far: $('#calendar').fullCalendar('renderEvent', my_event); $('#calendar& ...

embed a hyperlink onto a live video at a designated moment within an HTML document

Can anyone help me figure out how to overlay a link over a video playing at a specific time on an HTML page? I know it's easy to do on Youtube, but I need to accomplish this task without using Youtube. :) Thank you in advance for any assistance! ...

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...