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>