Animating an object in Three.js as it transitions smoothly between two different positions

If I have an object positioned at position.x = 0 and I wish to animate it smoothly to position.x = 2.435 in the render loop, how can I achieve this effect?

Answer №1

If you want to incorporate animations, consider utilizing the THREE AnimationMixer. The below function is designed to set up the animation process. Take a look at this jsFiddle example to see it in action.

For creating a moving animation, you can use the following function:
const createMoveAnimation = ({ mesh, startPosition, endPosition }) => {
  mesh.userData.mixer = new AnimationMixer(mesh);
  let track = new VectorKeyframeTrack(
    '.position',
    [0, 1],
    [
      startPosition.x,
      startPosition.y,
      startPosition.z,
      endPosition.x,
      endPosition.y,
      endPosition.z,
    ]
  );
  const animationClip = new AnimationClip(null, 5, [track]);
  const animationAction = mesh.userData.mixer.clipAction(animationClip);
  animationAction.setLoop(LoopOnce);
  animationAction.play();
  mesh.userData.clock = new Clock();
  this.animationsObjects.push(mesh);
};

Answer №2

Define a variable for your target position before entering the rendering loop:

let targetPositionX = 2.435;

Within the rendering loop, create an if statement to check if the object's X position is lower than the targetPositionX. If it is, increase the object's X position by a specified increment (adjust based on desired speed) until it reaches or exceeds the targetPositionX.

Example:

if (object.position.x <= targetPositionX) {
    object.position.x += 0.001; // Adjust the increment to control speed
}

Below is the complete rendering loop code:

function renderLoop(){

    // Render the scene
    renderer.render(scene, camera);

    // Check object's X position
    if (object.position.x <= targetPositionX) {
        object.position.x += 0.001; // Adjust the increment to control speed
    }

    // Call the renderLoop function again
    requestAnimationFrame(renderLoop);
}

Note:

For more intricate animations, consider using Tween.js for Three.js as it simplifies animation and allows for easing functions.

Explore Tween.js at:

https://github.com/sole/tween.js

If you're delving into Three.js, learning Tween.js is highly recommended.

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

Ways to manually conceal a popover using Bootstrap 5

I am attempting to generate multiple Bootstrap popover instances that can all be closed with a single click. Here is the approach I took: document.addEventListener('DOMContentLoaded', function () { var items = []; document.getElementBy ...

Tips for securely implementing JSON web tokens when integrating an external application with the WordPress REST API

I have a query regarding JWT. Let's consider this situation. A -> wordpress site with wp rest api enabled; B -> External application (for example, a simple javascript/jQuery app) Suppose I want to make a post request or create a new post on t ...

The combination of the card hover effect and the bootstrap modal creates complications

Hey there! I'm in the midst of crafting a webpage using Bootstrap and EJS. My aim is to craft a modal window that pops up when a specific button is clicked to display extra information, and upon clicking an X or "close" button, the modal should disapp ...

Tips for effectively validating with ParsleyJS remote validator?

I've been trying to solve a problem for hours now, but I can't seem to figure out how to retrieve a value in php and pass it back to js. Here is the input field in question: <input type="text" class="form-control input-lg" name="nr_ref" id=" ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

javascript An interactive accordion component created with Bootstrap

I have been searching for a solution to create an accordion-style collapsible set of panels where the panels remain separate and do not have headers. I want buttons on one side, and when clicked, a panel is displayed on the other side. Only one panel shoul ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

How can I trigger my function in jQuery after inputting into the jQuery text field?

Looking for advice on implementing a function in jQuery for a text field that is not working as expected. The code works fine when creating a text field in HTML, but encounters issues with the jQuery text field. <!DOCTYPE html> <html> <body ...

Adding custom data attributes to HTML tags in Vue.js

I have a question regarding adding a data attribute to the <html> element in vue.js (v2). I haven't been able to find any guidance on how to do this in the auto generated code or the documentation. The end goal is to achieve this desired output ...

Difficulty in getting callbacks triggered for basic conversation with Botkit 4 and SlackAdapter

Struggling to get conversation callbacks firing correctly. Has anyone successfully implemented botkit 4 with Slack and can share a working sample? I've set up the necessary adapters and middleware, but my callbacks just won't trigger. I followed ...

Mobile site experiencing slow scrolling speed

The scrolling speed on the mobile version of my website, robertcable.me, seems to be sluggish. Despite conducting thorough research, I have not been able to find a solution. I have attempted to address the issue by removing background-size: cover from my ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

What is the best method to display a component using a string in Vue 3?

I've been attempting to render a component from a string without success. Here are my codes: <template> <div v-html="beautifyNotification(notification)"></div> </template> <script> import { Link } from '@i ...

Error message: When using the Three.JS STL Loader, an Uncaught TypeError occurs because the property 'scale' is being called on an undefined value

I am currently loading five elements using the STL Loader in order to create a table. My goal is to use dat.gui to adjust the scale of Tabletop.STL. Here is the code snippet: <!DOCTYPE html> <html lang="en> <head> <title& ...

Is there another option besides PHP not being compatible with JavaScript?

I'm looking to dynamically change the properties of a div, so I've turned to using the jquery.keyframes plugin. The second class currently has a low-res blurred background image from the croploads directory. Now my goal is to switch it out for a ...

Dealing with problems related to types in React and TypeScript createContext

Struggling to pass the todos (initial state) and addNewTodo (methods) using React Context hook and typescript. Despite trying multiple solutions, errors persist. Partial generics do not cause issues in the context component, but I encounter the error Cann ...

Node.js (npm) is still unable to locate python despite setting %PYTHON% beforehand

Trying to get Node.js to work is proving to be more challenging than expected! Despite having two versions of Python on my computer, it seems that Node.js only works with the older version, 2.7. When I encountered an error, it prompted me to set the path ...

Leveraging vuejs to dynamically insert a URL within a function

I am attempting to dynamically bind an image path inside a method. It seems feasible, but I'm uncertain if I am implementing the code correctly. Can someone review it? Essentially, I want to retrieve the selected image from the model rather than hardc ...

Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have. function customCheck(username){ var result = "normal"; $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){ if(data.stream == null) re ...

I am facing an issue with Recharts not occupying the full width in my Nextjs/Reactjs project. Despite setting it to 100% width, it does not behave as

I am currently working with Recharts in combination with Next.js and Tailwindcss. I decided to create my own barchart by copying a code snippet from Recharts, but encountered an issue where changing the height to aspect worked fine, however setting the wid ...