Home > Net >  ThreeJS animate object to multiple positions using lerp
ThreeJS animate object to multiple positions using lerp

Time:02-11

I'm trying to animate the movement of a sphere along a predefined set of vertices. I'm able to animate from one point to another using the below code

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

this works for a single animation from initial position to (100, 2, 0). How do i keep on adding vertices, so that it will be animated in sequence.

CodePudding user response:

You can animate a mesh along a path with plain three.js by defining a curve based on your sequence of points and then using this curve for 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 ) );

  // 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 ); // animating

  renderer.render( scene, camera );

}
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>

  • Related