Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code:

let obj;
let camera = new THREE.PerspectiveCamera(fov, asp, near, far);
let scene = new THREE.Scene();
const loader = new THREE.GLTFLoader();
async function init() {
    obj = await loader.loadAsync("./public/modelo/scene.gltf");
    scene.add(obj.scene);
    animate(obj.scene.children[0]);
    renderer.render(scene, camera);
    function animate(objeto){
        console.log(objeto);
        requestAnimationFrame(animate);
        objeto.rotation.z += 0.005;
        renderer.render(scene, camera);
    }
}
init();

Initially, the function performs correctly, but subsequent calls are causing issues as seen in my console.log() output. The first run of animate() displays the object as expected. However, all following calls only return a rapidly increasing floating-point number. I double-checked the object's integrity after the initial function call, so I'm perplexed by this behavior. Any recommendations or insights?

Answer №1

One crucial issue lies within a specific line of your code:

requestAnimationFrame(animate);

Referencing the MDN documentation for requestAnimationFrame, the callback function you provide - in this case, animate, is:

The function that is executed when it is time to update your animation for the subsequent repaint. The callback function takes a single argument, a DOMHighResTimeStamp similar to the one returned by performance.now(), which indicates the time at which requestAnimationFrame() starts executing callback functions.

This essentially means that your animate function is being invoked with a timestamp, akin to a numerical value. This explains the behavior you are observing, as it is not receiving your "objeto" as an argument.

To rectify this, ensure that the callback function passes the correct argument to animate. Replace the previous call with the following:

requestAnimationFrame(() => { animate(objeto); });

Alternatively, as @Bergi suggests, you can circumvent the need for an argument altogether by defining objeto outside of animate, within the init function. Since you consistently call animate with the same argument, there is no necessity to explicitly pass it. Thus, your code can be simplified to:

async function init() {
    obj = await loader.loadAsync("./public/modelo/scene.gltf");
    const objeto = obj.scene.children[0];
    scene.add(obj.scene);
    animate();
    renderer.render(scene, camera);
    function animate(){
        console.log(objeto);
        requestAnimationFrame(animate);
        objeto.rotation.z += 0.005;
        renderer.render(scene, camera);
    }
}

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

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Set the Checkbox selections by utilizing the array values in the MUI DataGrid

In my MUI Datagrid, I have 2 columns for ID and City Name. There are only 3 cities represented in the table. Within a citizen object like this: const userMockup = { id: 1, name: "Citizen 1", cities: [1, 2], isAlive: true }; The cities ar ...

The only thing visible on my project is the homepage, void of any buttons or additional pages

After completing this school project, I believed that everything was done correctly. However, as I faced issues with the code, I decided to seek help and share my app.js and bin section for clarification. Starting it with npm on the localhost as shown in ...

Encountering a JavaScript problem in Google Chrome?

Something strange is happening when I try to place an image in the canvas... "Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideo ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

What is the best way to choose the next adjacent element using a CSS selector with Python Selenium?

The structure of the DOM is as shown below: <ul> <li> <a href="#" role="button" class="js-pagination link" data-page="1">1</a> </li> <li> <a href="#" role="button" class="js-pagination link active" data ...

The concept of CSS "preload" animation

When working with CSS, I encountered an issue with lag while loading 24 different mask images for a transition effect. To address this, I tried using a div called "preload" to cache the images and prevent lag on playback: <div class='trans' s ...

Uploading directly to AWS S3: SignatureDoesNotMatch error specifically for Internet Explorer users

My process involves using Amazon Web Service S3 for uploading and storing files. I create a pre-signed URL using the AWS SDK for Node.js on the server-side to enable direct file uploads from the browser through this signature URL. The Process On the serv ...

Employ material-ui default prop conditionally

I am implementing a StepLabel component in material ui. Depending on the props passed to the parent, I may need to make changes to the icon property of the StepLabel: interface Props { customClasses?: ClassNameMap; customIcon?: ReactNode; } const MySt ...

Leveraging anonymous functions within an IF statement in JavaScript

Can you explain how to implement an anonymous function within an if statement? Feel free to use the provided example. Thank you if(function(){return false;} || false) {alert('true');} For more information, visit https://jsfiddle.net/san22xhp/ ...

Validate user credentials using both jQuery and PHP to display an error message if login details are incorrect

Working on a form validation using jQuery and PHP. I am utilizing an .ajax request to the server in order to verify if data has been entered into the form, and execute different actions based on the callback response received from the server. For instance, ...

Exploring the benefits of utilizing express-session for authentication management

I am currently in the process of creating a basic login application using express 4 and express-session. When setting up my code as follows: app.use(session({ store: new MongoStore({ db: 'sess' }), secret: 'Ninja Turtle', cookie ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...

I'm looking to leverage axios and useState-useEffect to collect data from numerous web pages. Any suggestions on how to do this efficiently

I stumbled upon a URL that leads to an API with a total of 42 pages and 826 data entries. The URL is . My goal is to store all the data in one variable for future filtering purposes, especially when implementing a "show more" button feature. Initially, on ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

"Patience is key when it comes to waiting for an HTTP response

Looking for a solution in AngularJS, I have a service that calls the backend to get some data. Here is how the service looks: app.factory('myService', ['$http', '$window', '$rootScope', function ($http, $window, $ro ...

Locate all elements by a segment of the identification attribute

Is it feasible to achieve the following: I possess a collection of divs, all having IDs that conclude with '_font', such as 'body_font', 'heading_font', 'tagline_font', and so on. Is there a method to retrieve thes ...

Is there a way for me to dynamically incorporate new elements into this object?

I am working with an object msg.data that contains the following information: { "user_id": 1, "success": "true" } Now, I want to add a name field to this list: { "user_id": 1, "success": "true", "name" : "giri" } I have attempted the following ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...