Mesh in THREE.js experiencing jittering issues when global position is set

I have created a function called moveToPoint in order to set the global position of an object. This function takes in a world point x y z, converts it to the local coordinate system, and then updates the object.position to go to that new local coordinate.

However, when I use this function in the animation loop, I notice a strange jittering artifact occurring. I am puzzled by this issue as the code seems simple and straightforward.

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32);
const sphereMaterial = new THREE.MeshBasicMaterial({
  color: 0xffffff
});
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(0, 0, 0);
scene.add(sphere)


camera.position.z = 5;


function moveToPosition(object, x, y, z) {
  const pos = new THREE.Vector3(x, y, z);
  object.worldToLocal(pos);
  object.position.copy(pos);
}


function animate() {
  requestAnimationFrame(animate);

  moveToPosition(sphere, 0, 1, 0);

  renderer.render(scene, camera);
};

animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>

Any help or guidance on this matter would be greatly appreciated.

Answer №1

Essentially, you are alternating the Y-position between 0 and 1 repeatedly.

Let's break it down frame by frame:

Frame 1:

  • Starting sphere position: 0, 0, 0
  • worldToLocal() sets pos to 0, 1, 0
  • Ending sphere position: 0, 1, 0

Frame 2:

  • Starting sphere position: 0, 1, 0
  • worldToLocal() sets pos to 0, 0, 0
  • Ending sphere position: 0, 0, 0

... and so forth

Another perspective:

  • Frame 1:
    [0, 0, 0].worldToLocal([0, 1, 0]) = [0, 1, 0]
  • Frame 2:
    [0, 1, 0].worldToLocal([0, 1, 0]) = [0, 0, 0]

Solution:

Given that the sphere is not nested within any other objects, you can eliminate the worldToLocal() call. This method is typically necessary for dealing with nested objects, not directly added ones in the scene.

To illustrate, I've created a basic sine-wave animation from -1 to +1:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32);
const sphereMaterial = new THREE.MeshBasicMaterial({
 color: 0xffffff
});
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(0, 0, 0);
scene.add(sphere)

var axesHelper = new THREE.AxesHelper(2);
scene.add(axesHelper);

camera.position.z = 5;


function moveToPosition(object, x, y, z) {
 const pos = new THREE.Vector3(x, y, z);
 //object.worldToLocal(pos);
 object.position.copy(pos);
}


function animate(t) {
 requestAnimationFrame(animate);
 
 // Sin movement from -1 to +1
 const yPos = Math.sin(t / 1000);
 moveToPosition(sphere, 0, yPos, 0);

 renderer.render(scene, camera);
};

animate(0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.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

How can a string be transformed into a JavaScript Object without using JSON?

I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}'). But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")? The outcome of this example is a ...

JQuery continuously firing off AJAX requests

Currently, I am experimenting with using a Jquery Ajax request to incorporate an AutoComplete feature. This involves utilizing ElasticSearch on the backend for data retrieval. This is what my autocomplete.html looks like: <!DOCTYPE html> <html l ...

Refining the nodes and connections within a directed graph by implementing a filter triggered by clicking a button

I have successfully implemented a force-directed graph. My next step is to incorporate buttons in the main HTML data to enable further filtering. Unfortunately, I haven't been able to make it work yet. I would greatly appreciate any suggestions or gui ...

Innovative application transforms rigid input with dynamic hyphens

I am currently working on an input field specifically designed for Social Security Numbers (SSNs). My aim is to have an input with pre-placed hyphens, allowing the user to simply enter their 9-digit SSN while the numbers automatically space themselves arou ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...

Do cookies stored with the document.cookie method specific to the current webpage?

I have been working with cookies in my asp.net web application using JavaScript to store various values. I am currently using document.cookie to save these values as a lengthy string. However, I am encountering an issue where the value I save in the cookie ...

Tips for directing focus to a specific div or success message following a form submission

After numerous attempts, I am still struggling to focus on the success message following form submission. The backend PHP code is already in place to upload data into the database and display the success message, but every time I submit the form, the page ...

Is it possible to use Ajax to prompt a pop-up window for basic authentication when logging in?

While attempting to access the reed.co.uk REST web API in order to retrieve all related jobs, I am encountering an issue. Despite passing my username and password, a popup window keeps appearing when I call the URL. The alert message displayed reads: i ...

Retrieve JSON data upon refreshing the page

In my blogging application, each post has its own unique permalink structure, such as /post/Dh3hdjs* where Dh3hdjs* represents the specific permalink. However, I am facing an issue where after successfully creating a post and being redirected to the specif ...

Mastering the art of utilizing defer/async attributes in script tags effectively

When I add the "defer" attribute to all external js files, Owl Carousel fails to load and shows an error that "$" is not defined. However, if I remove the defer attribute from the script tag, everything works fine without any errors. Unfortunately, I am un ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

What is an alternative method to retrieve POST fields in Express without relying on the bodyParser middleware?

Recent updates to Express have suggested to stop using the bodyParser middleware, as indicated by a debug message. Upon further research, it appears that bodyParser is simply a wrapper to the json and urlencoded middlewares. In its place, the latest versio ...

Strategies for avoiding the issue of multiple clicks on a like button while also displaying an accurate likes

My latest project involves creating a Like button component that features a button and a likes counter text field. The challenge I am facing is that each time I click on the button, it toggles between like and dislike states. However, if I rapidly press ...

Unable to access attribute of instantiated class

I am relatively new to TypeScript and I recently encountered a problem that's stumping me. I'm working on setting up a REST API using Express. The setup involves a router that calls a controller, which in turn invokes a service method before ret ...

Javascript functions correctly when the HTML file is opened locally, however, it encounters issues when accessed through an http-server

My HTML file includes an embedded web widget from tradingview.com with the following code: <!-- TradingView Widget BEGIN --> <span id="tradingview-copyright"><a ref="nofollow noopener" target="_blank" href="http://www.tradingview.com" style ...

Guide on establishing two loops in React JS

I'm receiving a JSON array that contains nested arrays. I attempted to iterate through it using two loops, but so far, I haven't been successful. {this.state.listOfAlarms && this.state.listOfAlarms.map((alarms) => {alarms.repo ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...

Is it Possible to Customize the Appearance of a Broken Link Using CSS?

Can you change the color of broken links on your site to distinguish them from working ones? For example, making working links blue and broken links red. If CSS is not an option, is it possible to use JavaScript to detect broken links and style them diffe ...