J Marsh
J Marsh

Reputation: 3

ThreeJS calculation for object in relation to camera position and orientation

It seems like this would be a pretty common problem, but I can't find an example online and I'm too much of a math noob...

Using ThreeJS, I have a library to do spatial audio positioning (https://github.com/tmwoz/hrtf-panner-js) based on user position, but my code assumes the camera looks straight ahead and doesn't move. Since my camera is moving, I need to get the xyz position of a 3D object in relation to the camera's position and orientation.

//finds the object in world coordinates
var p = new THREE.Vector3();
p.setFromMatrixPosition(visual.object.matrixWorld);
this.audioTrack.updateHrtf(p.x, p.y, p.z);

How do a translate the object into camera-space coordinates? Thanks for your help!

Note: I know that the WebAudio API has a mechanism to do this simply, but it doesn't have the power of the HRTF (Head Related Transfer Function) library, which sounds much better.

Upvotes: 0

Views: 1062

Answers (1)

WestLangley
WestLangley

Reputation: 104783

To transform a Vector3 vec from world space to camera space, do this:

camera.matrixWorldInverse.getInverse( camera.matrixWorld );

vec.applyMatrix4( camera.matrixWorldInverse );

three.js r.73

Upvotes: 2

Related Questions