Skip to content

Instantly share code, notes, and snippets.

@BarakChamo
Created November 4, 2019 23:19
Show Gist options
  • Save BarakChamo/9ed37256e29b78d28ff5176d6264746a to your computer and use it in GitHub Desktop.
Save BarakChamo/9ed37256e29b78d28ff5176d6264746a to your computer and use it in GitHub Desktop.
THREE.js move camera along path with lookAt target
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 50, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.up = new THREE.Vector3(0,0,1);
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x005E99 } );
var cube = new THREE.Mesh( geometry, material );
cube.position.set(1,10,1);
scene.add( cube );
camera.position.z = 30;
var curve = new THREE.CubicBezierCurve3(
new THREE.Vector3( -10, 0, 0 ),
new THREE.Vector3( -5, -15, 0 ),
new THREE.Vector3( 20, 15, 0 ),
new THREE.Vector3( 10, 0, 0 )
);
var points = curve.getPoints( 50 );
var geometry = new THREE.BufferGeometry().setFromPoints( points );
var material = new THREE.LineBasicMaterial( { color : 0xffffff } );
// Create the final object to add to the scene
var curveObject = new THREE.Line( geometry, material );
scene.add(curveObject);
var clock = new THREE.Clock()
clock.start()
var speed = 0.5
var pathTarget = new THREE.Vector3(0,0,0)
var render = function () {
curve.getPoint((clock.getElapsedTime() * speed) % 1.0, pathTarget)
// cube.position.copy(pathTarget)
camera.position.copy(pathTarget)
camera.lookAt(cube.position)
requestAnimationFrame( render );
// cube.rotation.x += 0.1;
// cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment