Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Orientation of Camera in THREE.js

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!

like image 282
Cabbibo Avatar asked Dec 24 '12 16:12

Cabbibo


3 Answers

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

like image 149
WestLangley Avatar answered Oct 17 '22 14:10

WestLangley


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

camera.getWorldDirection()

to get the camera orientation vector.

like image 2
pkout Avatar answered Oct 17 '22 15:10

pkout


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;

}

like image 2
Joris Avatar answered Oct 17 '22 14:10

Joris