Animating three-dimensional objects using Three.js in real-time

I have been working with three.js and have successfully animated some objects using the animate() function. Here's a snippet of my code:

function animate(){
    object.position.z++;
}

The issue I'm facing is that this function is called every rendered frame, leading to varying speeds for my object on devices with different framerates. Is there a way to synchronize the animation based on seconds or milliseconds?

Thank you!

Answer №1

Another option is to use THREE.Clock() within the realm of three.js:

var clock = new THREE.Clock();
var speed = 2; //units a second
var delta = 0;

render();
function render(){
  requestAnimationFrame(render);

  delta = clock.getDelta();
  object.position.z += speed * delta;

  renderer.render(scene, camera);
}

Check out this jsfiddle example r86

Answer №2

requestAnimationFrame calculates the time elapsed since the page loaded and includes it in the callback function. Personally, I prefer working with time in seconds, but the provided time is in milliseconds.

let then = 0;
function animate(now) {
  now *= 0.001; // converting to seconds

  const delta = now - then;
  then = now;

  object.position.z += delta * speedInUnitsPerSecond;

  ...

  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

PS: It's surprising this information isn't already on Stack Overflow. It might be buried somewhere, though. RequestAnimationFrame and its usage in Three.js have likely been discussed before, just maybe not in the specific context mentioned here.

For further reading, check out: Best options for animation in THREE.JS

Answer №3

If you want to achieve smooth animations in Three.js, consider using TWEEN library. For a step-by-step guide on how to use TWEEN, check out this tutorial:

Implementing TWEEN is quite simple:

  new TWEEN.Tween(object.position).to(targetPos, 200).start().onComplete(()=>{
      //Perform actions when animation is complete
  });

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

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

Determining if data from two separate lists in Vue.js matches in order to display in the template

I need to compare two sets of data - one fetched from the server and the other being default data. Data retrieved from the server: [ { "id": 7, "day": "14 April 2017", "time_list": [ { "id": 25, "time": "11:00 AM", ...

Utilizing CodeIgniter for Efficient AJAX Posting

I'm struggling to submit a post using the ajax post method. It appears that the request is being posted without any error messages, but the model doesn't seem to respond and insert the row into the database. While I'm not well versed in jQu ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Issue encountered while performing an Upsert operation on Pinecone using Node.js

Oops! PineconeArgumentError: The argument provided for upsert contains type errors: the argument should be an array. Package "@pinecone-database/pinecone": "^1.0.0", Inquiry const index = pinecone.Index(process.env.PINECONE_INDEX_NAME ...

How can I retrieve a variable in a JavaScript AJAX POST request?

Similar Question: How to retrieve a variable set during an Ajax request I am facing a challenge, as I am making an ajax call and receiving a number as the response. My query is, how can I assign this returned number to a variable that is accessible ou ...

At the ready stance for a particular grade of students attending a class

I have created a page with a navigation menu that can be scrolled using the wheel mouse. My goal is to ensure that the li item with the 'selected' class is always positioned in the first position on the left. Is there a way to achieve this using ...

ASP.NET repeater causing jQuery scrollTop to malfunction after first use

I am facing a peculiar issue where I need to scroll through repeater items in a RadWindow using arrow keys in an ASP.NET application. Below is the code snippet: function isScrolledIntoView(elem) { var docViewTop; var docViewBottom ...

The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show option ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

What will the relationships be like between the models using Sequelize?

Hello there, I'm seeking assistance in establishing the correct associations between models using Sequelize. In my project, I have three types of products, each with unique attributes as well as shared attributes. ...

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

Vanishing Edge in THREE.js Geometry

My current project involves creating a 3D L-shape using principles of Geometry. I start by adjusting the vertices and faces for the top portion of the L, then move on to the bottom section. Finally, I manipulate the faces for the sides utilizing the alrea ...

An error of '______ is not defined' was thrown, I'm puzzled as to why

I keep encountering an error that says "weekday is not defined". I'm unsure of the reason behind this issue. Any assistance would be greatly appreciated! (function(exports) { var days = ["monday", "tuesday", "wednesday", "thursday"]; exports. ...

'AngularJS' filtering feature

I am dealing with an array of objects and I need to extract a specific value when a key is passed in the 'filter' function. Despite my best efforts, the controller code snippet provided below returns an undefined response. Can someone please assi ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

Rearranging table rows with jQuery based on numerical values within child elements

I require assistance in sorting the rows of a table based on the numbers within certain anchor tags. Below is an example of the table structure: <table id="sortedtable" class="full"> <tbody> <tr> <th>Main tr ...

Issue with VUE JS: Score not increasing on click event as desired

Greetings! I've been working on a basic game that increments the score by 1 when the user clicks a button. new Vue({ el: '#MyApp', data: { score: '10', }, methods: { ScoreIncre: function(incre) { this.score ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...