javascripthtmlthree.jsweb-audio-api

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!


Solution

  • 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.

    // 1. Pick a point in front of the camera in camera space
    const pLocal = new THREE.Vector3( 0, 0, -1 );
    
    // 2. Transform that point into world space
    const pWorld = pLocal.applyMatrix4( camera.matrixWorld );
    
    // 3. Construct the desired direction vector
    const dir = pWorld.sub( camera.position ).normalize();
    

    EDIT: Updated for three.js r.57

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