Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below:

function animate() {
  requestAnimationFrame(animate)
  sphere.position.lerp(new THREE.Vector3(100, 2, 0), 0.05)
  render()
}
function render() {
  renderer.render(scene, camera)
}
animate()

While this method works for a single animation from the starting position to (100, 2, 0), I am wondering how I can continue adding more vertices to create a sequential animation path.

Answer №1

If you want to create animation of a mesh moving along a path using plain three.js, you can achieve this by first defining a curve based on your sequence of points and then utilizing this curve for the animation.

let camera, scene, renderer, clock;

let mesh, path;

const duration = 10;
let time = 0;

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
  camera.position.set( 3, 2, 3 );

  scene = new THREE.Scene();
  
  renderer = new THREE.WebGLRenderer( { antialias: true } );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );
  
  clock = new THREE.Clock();

  const controls = new THREE.OrbitControls( camera, renderer.domElement );

  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshNormalMaterial();
  mesh = new THREE.Mesh( geometry, material );
  scene.add( mesh );

  scene.add( new THREE.AxesHelper( 2 ) );

  // Define points and path

  const points = [ 
    new THREE.Vector3( 0, 0, 0 ), 
    new THREE.Vector3( 1, 2, - 2 ),
    new THREE.Vector3( 2, 2, - 0.5 ),
    new THREE.Vector3( 2, 1, - 2 ) 
    ];

  path = new THREE.CatmullRomCurve3( points, true );
    
  // Visualize the path

  const lineGeometry = new THREE.BufferGeometry().setFromPoints( path.getPoints( 32 ) );
  const lineMaterial = new THREE.LineBasicMaterial();
  const line = new THREE.Line( lineGeometry, lineMaterial );
  scene.add( line );
  
}


function animate() {

  requestAnimationFrame( animate );
  
  time += clock.getDelta();
  
  const t = Math.min( time / duration, 1 );
  
  if ( t === 1 ) time = 0;
  
  path.getPointAt( t, mesh.position ); // Animation happening here

  renderer.render( scene, camera );

}
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04706c76616144342a3537332a31">[email protected]</a>/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15617d67707055252b2426223b20">[email protected]</a>/examples/js/controls/OrbitControls.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

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

What is the best method for establishing a page location during rendering/onload?

It seems like there is a JavaScript event happening here using the onload attribute. But for the life of me, I can't seem to crack this code. <body onload="moveToHere('reference')"> I'm stuck and could really use some assistance ...

Issue detected in the timing of the Three.js animation loop

I’ve been diving into the world of three.js and conducting some experiments. I decided to showcase a 3D model on a specific section of my HTML/CSS website by creating a div and embedding the canvas inside it. Once the model loaded successfully, my focus ...

How can one determine the direction towards the camera from a vertex in a vertex shader using GLSL?

I'm working with the following code snippet: vec4 localPosition = vec4( position, 1.); vec4 worldPosition = modelMatrix * localPosition; vec3 look = normalize( vec3(cameraPosition) - vec3(worldPosition) ); vec3 transformed = vec3( position ) + look; ...

What could be the reason behind the ajax call not getting triggered?

Upon page load, the first alert is displaying correctly. However, the alert inside the ajax call is not triggering. It appears that the ajax call itself is not functioning as intended - it is supposed to invoke a method in the controller, but no longer s ...

What are the best techniques for enhancing A-Frame HTML shader text for immersive VR experiences?

Greetings everyone! I've been working on creating a virtual reality book page that is attached to the user's hand using A-FRAME with Oculus-Go. Initially, I attempted to use a plane and apply text to it using the text attribute with defined value ...

Three.js combined with Ember.js

I've been brainstorming ways to merge Ember.js with Three.js. My goal is to render multiple elements, manage the data with Ember.js bindings and general pub/sub handling, while also being able to manipulate the views/elements with three.js using THREE ...

jquery for quick search

<form method="post" action="search.php"> Commence search: <input id="search" type="text" size="30" > <div id="search_results"></div> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script src="//code. ...

Transforming arrays into nested objects using JavaScript

My array consists of objects structured like this: var exampleArray = [{ name: 'name1', subname: 'subname1', symbolname: 'symbol1' }, { name: 'name1', subname: 'subname11', symbolname: 'sy ...

Displaying infowindow pop-ups on random markers on Google Maps every 3 seconds

Here lies the challenge. I am tasked with creating a Google map that displays multiple markers. Each marker must have a unique info window with distinct content. Upon opening the website, an info window randomly appears on one of the markers after 3 sec ...

What is the method to make a CSS selector avoid selecting a specific element?

Let's say I have a CSS style that looks like this: input.validation-passed {border: 1px solid #00CC00; color : #000;} The JavaScript validation framework I am using injects every input tag with a class="validation-passed". While this works fine ...

After refreshing, the other items stored locally are lost once a new item is added

After refreshing the page, only the item added remains and the rest are lost. How can I make sure all items persist? Here is my code snippet: let buttonsDom = document.querySelectorAll(elementsStr.itemsBtn) const buttons = [... buttonsDom] window.addEven ...

Customizing the design of vuetify table header to your liking

My goal is to implement a custom style for v-data table headers using the fixHeader method. The CSS code is intended to keep the header fixed in place even when scrolling horizontally. The issue arises as the style is applied to the inner <span> ele ...

Loading content dynamically with AJAX and enabling smooth page scrolling

Looking for a solution to this issue. I have a button on my webpage that, when clicked, uses AJAX to load content into a "div" element below the button. Everything functions properly except for one problem - every time the button is pressed, the page scrol ...

Restrict the height of posts created in the summernote editor

My goal is to create a structured page application using summernote. When using summernote, a div with contenteditable=true is appended to the body to allow users to add content. However, I want to set a fixed height for this div so that users can only ent ...

I am having trouble getting Google Maps to load

Why does the map on my website only load when the browser window is resized? Below is the JavaScript code being used: <div class="map-cont"> <div id="map" class="location-container map-padding" style="width:100%;height:400px;background:y ...

When attempting to call an XML node with JavaScript in an HTML file within Dreamweaver, the functionality works as expected. However, upon testing the same code on a server

As a beginner in Javascript, I am attempting to use document.write to display some XML data in an HTML format. Below is the code that I have been working on: <script> function loadXMLDoc() { if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest( ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...