1
votes

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>
1
If the camera is at x, y, z, then the current distance is Math.sqrt(x*x + y*y + z*z). Take each coordinate, multiply it by the new distance, then divide it by the calculated distance. (this works because the camera is looking at the origin; to move it back in general you need to add a negative multiple of its view vector to its position)Chris G
camera.position.setLength(13) does the trick.prisoner849

1 Answers

1
votes

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/ ]