Updating the positions of Mesh objects in Three.js asynchronously

I'm currently working on a Three.js application where I am creating a grid to display various objects. These objects are rendered on the grid based on their positions, which are obtained from data fetched from a REST API that I poll every 300 milliseconds. Presently, I am making the fetch calls within the animate() function and checking if 300ms have passed since the last request. Once I retrieve the data from the API, I iterate through all mesh objects and update their positions to reflect the new data.

However, I am encountering an issue with the smooth movement of the objects between positions - they seem to "jump" on the grid when the new position is set. How can I ensure that the objects move smoothly? Is there a more efficient way to update object positions and handle asynchronous data from the API?

I haven't included my code here as it is quite lengthy and not entirely relevant...

EDIT: - additional information

Within my animate function, I fetch data in order to add new objects to the scene or update the positions if the item already exists. Here's an example of the code snippet to help illustrate what I am trying to achieve:


const objects = {}; // This holds all Mesh objects in the scene

function animate(){
    if (new Date().getTime() - lastTime > 300){
        axios
        .get(DATA_URL)
        .then(data => {
            /** Data is an array of objects to be added or updated in the scene.
             *  I iterate over the data array to check if the item already exists
             *  in objects or not. If it does exist, I update the Mesh positions,
             *  otherwise, I create a new mesh and add it to the scene.
*/
            data.forEach(item => {
                let mesh;
                if (objects[item.id]){
                    mesh = objects[item.id]
               }else{
                 mesh = // Create new mesh
                 objects[item.id] = mesh
               }

              // update position
               mesh.position.set(item.x, item.y, item.z);
           })
        })
     }
}

Answer №1

If I understand correctly, one possible solution is to use the Tween.js library for this task:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(1, 2, 3);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);

var items = [];
setInterval( addItem, 300);

function addItem(){
  var tween = new TWEEN.Tween({val:0}).to({val:1}, 100).onUpdate(
    function(value){
      items.forEach(v => {
        v.position.z -= value.val * 0.5;
      })
    }
  ).onComplete(item)
  .start();
}

function item(){
  var item = new THREE.Mesh(new THREE.SphereGeometry(0.25, 4, 2), new THREE.MeshBasicMaterial({color: Math.random() * 0xffffff, wireframe: true}));
  scene.add(item);
  items.push(item);
}

render();
function render(){
  requestAnimationFrame(render);
  TWEEN.update();
  renderer.render(scene, camera);
}
body{
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/91/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>

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

Rule for restoring scroll position upon reloading web pages in browsers

When it comes to websites that handle data asynchronously, the behavior of scroll position restoration upon browser refresh can vary. Sometimes the scroll position is preserved, while other times it is not. For example, when reloading after scrolling down ...

What could be causing the error message to appear stating that each list item must have a unique key when utilizing react-bootstrap in Nextjs?

My file currently contains keys for each child component, but it is still raising an error internally. I am unsure if I can resolve these issues on my own. export default function SecondaryNav(props:NavItems) { const router = us ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

Real-time File Updates Display with Node.js and Express.js

Seeking guidance on whether there is a Node module available to utilize the Express module for displaying real-time updates in the browser using data from a file. I have a regularly updated .csv file and I am looking to showcase these updates instantly on ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...

Error encountered upon initializing Node-RED due to the presence of an unexpected token while incorporating the NPM module "file-exists" into the

Currently, I'm in the process of developing an application using Node-RED and I'm looking to incorporate some NPM modules into my project. One particular module from James Thom caught my attention, called node-red-contrib-npm, which automates the ...

Retrieving Array keys from PHP using jQuery

As a beginner in jQuery, I am eager to learn how to retrieve Array keys from a php file using jQuery. Currently, I have jQuery code set up to send input to file.php and execute a query on every keyup event. When file.php echoes the result, it looks somet ...

I'm curious if there is a method in Vue.js that allows for creating a separator while utilizing v-for, much like the way `Array.join()` or FreeMarker's `<#sep>` functions operate

My goal is to create a list of <span> elements separated by commas using vue.js and v-for. Is there an easy way to achieve this in vue.js? In JavaScript, I would typically use users.join(", "). In FreeMarker templates, you can do some very interes ...

How to use JavaScript to retrieve extensive data streams (exceeding 1GB) from the internet

I'm interested in finding out if there is a way to stream data directly from JavaScript to the browser's download manager. With WebRTC, I am able to stream large amounts of data (files over 1GB) from one browser to another. On the receiving end, ...

Fade out the notification div when the user clicks anywhere outside of it

I am currently working on a website with a notification feature. When the user clicks on the notification button, a notification box will appear at the bottom of the button. I would like the behavior of this notification to be similar to Facebook's - ...

What is the correct method to authenticate a user's ID token in Firestore with Javascript?

I am in the process of developing a react native application and have integrated Firebase, specifically firestore, for data management purposes. My current goal is to incorporate an automatic login feature in my app, where users remain signed in even after ...

retrieving data from a node and embedding it into an HTML file

In my project, I have an index.html file and an app.js nodejs file. Within the app.js file, there is a variable named "name" that I would like to display in my index.html page. Here is the code snippet: var name = "Utsav"; var HTTP = require('HTTP&a ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

Is it possible for jQuery to detect if an email was sent from the client's email account?

I am working towards a feature on my website where users fill out specific fields and then click "send email" to activate their email platform via "mailTo", with the email pre-populated for easy sending. The challenge lies in confirming if the user actuall ...

Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common f ...

Retrieving information from AngularJS modal window

Seeking a solution to retrieve data FROM modal to invoking controller, as most examples only cover sending data TO the modal. What is the proper method for achieving this? Here is the form used within the modal: <form class="form-horizontal"> < ...

Having trouble deactivating date selections in Vue.js Material Datepicker

Can someone assist with the following HTML code: <datepicker :date="child" :option="option" v-model="child.dob" @change="updatechildDOB(child)" :disabled="disabled"></datepicker> Here are the available options: option: { type: 'd ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Introduce a fresh parameter into the promise all chain

I am using the code below and it is functioning as expected. However, I now need to incorporate the modifyOpt() function. Currently, the code works and returns args[2] but I also need to include another step... I want to pass the return value (port) from ...

Can you explain the distinction between locating an element by its class name versus locating it by its CSS selector?

Class name: var x = document.getElementsByClassName("intro"); CSS selector: var x = document.querySelectorAll("p.intro"); I'm a bit puzzled, are there any distinctions between the two methods or are they essentially the same? ...