Smooth Camera


This example features simple player input controls with a smooth 3rd person follow camera.

Simply handles user input with document.onkeydown events and applies it accordingly to player mesh.

this.input = {x:0 ,y:0};
 
document.onkeydown = function myFunction() 
    {
        switch (event.keyCode) {
        case 38:
            //UP
            this.input.y = 1;
            break;
        case 40:
            //DOWN
            this.input.y = -1;
            break;
        case 37:
            //RIGTH
            this.input.x = -1;
            break;
        case 39:
            //LEFT
            this.input.x = 1;
            break;
        }
    }

Apply player matrix to camera matrix with an offset. Finally interpolate between the current camera position and the desired camera position with Math.lerp function.

function followCamera()
{
    //Offset from camera to player
    var relativeCameraOffset = new THREE.Vector3(0,5,10);

    //UPDATE PLAYER WORLD MATRIX FOR PERFECT CAMERA FOLLOW
    player.updateMatrixWorld()
    //Apply offset to player matrix
	var cameraOffset = relativeCameraOffset.applyMatrix4( player.matrixWorld );


    //SMOOTH CAMERA POSITION TO TARGET POSITION
    camera.position.lerp(cameraOffset, 0.1);
    camera.lookAt( player.position );
}