How would you move a camera backwards and forwards from a fixed point along the trajectory that it is facing?
I know there are several control scripts that do this but I need to do something custom and I'm not able to break down their code to figure how to isolate the above behaviour.
I've seen this answer which I think addresses the question and have come up with this code:
cameraPosition = camera.position
cameraRotation = new THREE.Vector3(camera.rotation._x, camera.rotation._y, camera.rotation._z)
newCamera = new THREE.Vector3().addVectors(cameraPosition, cameraRotation)
camera.position.set(newCamera.x, newCamera.y, newCamera.z)
camera.updateProjectionMatrix()
But this seems to move the camera in a circle rather than backwards and forwards.
Any help would be much appreciated. Thank you!
To move the camera forward or backward the direction it is facing, use
camera.translateZ( - distance );
or
camera.translateZ( distance );
three.js r.78
Here's how you do it by updating the camera.position.z
. Use the W
=forward, S
=backward
var camera, scene, renderer, geometry, material, mesh;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 500;
scene.add(camera);
geometry = new THREE.CubeGeometry(200, 200, 200);
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
document.body.addEventListener( 'keydown', onKeyDown, false );
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render(scene, camera);
}
function onKeyDown(){
switch( event.keyCode ) {
case 83: // up
camera.position.z += 50;
break;
case 87: // down
camera.position.z -= 50;
break;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With