How to get Orientation of Camera in THREE.js

15,032

Solution 1

You want to know the direction in world space in which the camera is looking.

In camera space, the camera is located at the origin and is looking down it's negative z-axis.

Pick a point in front of the camera in camera space:

var pLocal = new THREE.Vector3( 0, 0, -1 );

Now transform that point into world space:

var pWorld = pLocal.applyMatrix4( camera.matrixWorld );

You can now construct the desired direction vector:

var dir = pWorld.sub( camera.position ).normalize();

EDIT: Updated for three.js r.57

EDIT: Also see: three.js set and read camera look vector

Solution 2

In revision 69 (not sure in what revision it was introduced), you can call

camera.getWorldDirection()

to get the camera orientation vector.

Solution 3

if your camera is a child of the player object .e.g. in FPS game. Do the same calculation on the player (parent of camera) , and use this (the Bullit gets the right direction, in this case from obj)

Bullit.prototype.getDirection=function(obj){
this.position.add(obj.position);
var pLocal = new THREE.Vector3( 0, 0, -1 );
var pWorld = pLocal.applyMatrix4( obj.matrixWorld );
var dir = pWorld.sub( obj.position ).normalize();
this.direction=dir;

}

Share:
15,032
Cabbibo
Author by

Cabbibo

Updated on July 29, 2022

Comments

  • Cabbibo
    Cabbibo almost 2 years

    I am creating a 3d game using THREE.JS and the Web Audio API. One of the problems I am having is that I want to use the web audio Listener orientation, and define the listener to be the camera, whose position and direction are constantly being updated

    My question, is there anyway to easily get the vector direction of a THREE camera?

    I was trying to calculate it by using the old camera position, and using the velocity vectors to calculate which way it is facing, but this won't work when the camera is standing still...

    Would it be feasible to create a unit vector by getting using camera.rotation.x, camera.rotation.y, camera.rotation.z ?

    or is there an even easier way?

    Thanks so much for your time!

  • Cabbibo
    Cabbibo over 11 years
    PERFECT! Thank you so much!
  • Agent Zebra
    Agent Zebra almost 9 years
    What does applyMatrix4 do?
  • Joris
    Joris almost 9 years