Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move camera backwards and forwards in Three js

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!

like image 713
bravokiloecho Avatar asked Jun 30 '16 09:06

bravokiloecho


2 Answers

To move the camera forward or backward the direction it is facing, use

camera.translateZ( - distance );

or

camera.translateZ( distance );

three.js r.78

like image 190
WestLangley Avatar answered Oct 27 '22 18:10

WestLangley


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>
like image 41
Stubbies Avatar answered Oct 27 '22 18:10

Stubbies