7

Say I have a camera placed at:

{
  x: 10,
  y: 30,
  z: 20
}

It's rotation is:

{
  x: 0.1,
  y: 0.2,
  z: 0.3
}

I want to move the camera 1 unit from it's current position in the direction it's facing.

How do I do calculate the cameras new position?

I'm using ThreeJS.

WestLangley
  • 102,557
  • 10
  • 276
  • 276
arpo
  • 1,831
  • 2
  • 27
  • 48

3 Answers3

17

The THREE.Camera class extends the THREE.Object3D class. You can get the camera direction with the getWorldDirection method from the base class:

It returns a vector representing the direction in which the camera is looking, in world space.

When you have this direction vector you can use it to move the camera in the desired direction:

var direction = new THREE.Vector3();
camera.getWorldDirection( direction );

To move only 1 in that direction you can simply do:

camera.position.add( direction );

If you want to move more you could for example use the multiplyScalar method from the THREE.Vector3 class and multiply with the desired distance.

distance = 10;
camera.position.add( direction.multiplyScalar(distance) );
Wilt
  • 41,477
  • 12
  • 152
  • 203
  • THREE now complains ".getWorldDirection() target is now required" so you can pass it a Vector3 and then `direction = camera.getWorldDirection(vector);' returns the result into 'direction' and also put's it in the new vector. The reasoning for the change, written by WestLangely who posted the efficient answer below, is here: https://github.com/mrdoob/three.js/issues/12231 – KellyCode Dec 18 '18 at 15:53
  • @kellycode Thanks for your comment. I updated the answer so it is working with the latest three.js version. I also updated the broken links. – Wilt Dec 18 '18 at 19:56
5

The camera looks down its local negative-z axis. So to move the camera in the direction it is facing, use this method:

camera.translateZ( - distance );

This is the most-efficient method.

three.js r.78

WestLangley
  • 102,557
  • 10
  • 276
  • 276
0

For anyone who is using React Three fiber :->

    let a = perspCamRef.current.rotation.x
    let b = perspCamRef.current.rotation.y
    let c = perspCamRef.current.rotation.z
    var direction1 = new THREE.Vector3(a, b, c);
    let direction = perspCamRef.current.getWorldDirection(direction1)
    let distance = 1;
     perspCamRef.current.position.add(direction.multiplyScalar(distance));
Arshad
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 09 '23 at 08:58