Search code examples
javascriptthree.jsperspectivecamera

Set distance of THREE.PerspectiveCamera without change view direction


I have PerspectiveCamera in THREE.js somewhere in space as children of mesh. The camera should still look at the mesh (local coordinates [0, 0, 0]). I would like to change distance of camera from the mesh without change of view direction. Is there any easy way to do this?

camera.position.z = 13 // Works only if position.x and position.y are 0.
camera.setDistanceFromTarget(13) // I need something like this.

I just thinking about manual calculation of the actual camera's rotation angles and new camera's position. Here is fiddle.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement);

var geometry = new THREE.BoxGeometry(3, 3, 3);

var cube = new THREE.Mesh(geometry);
scene.add(cube);
cube.add(camera);

camera.position.set(2, 4, 6)
camera.lookAt(cube.position)

function animate() {
	requestAnimationFrame(animate);
	renderer.render(scene, camera);
}

animate();

// How to set distance of camera from [0, 0, 0] to 13 without change view direction?
camera.position.z = 13;
<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8>
		<title>THREE.js camera demo</title>
	</head>
	<body>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>
	</body>
</html>


Solution

  • You need to normalize the camera position vector, and then scalarly multiply it by the desired length:

    camera.position.normalize().multiplyScalar(13)
    

    [ https://jsfiddle.net/0jnw5guo/ ]