Three.js: Get the Direction in which the Camera is Looking

后端 未结 4 1875
离开以前
离开以前 2020-12-08 01:40

I\'m creating game in using html5 and THREE.js, and I have a camera that rotates with the euler order of \'YXZ\'.

This is so the camera rotation up, down, left and r

相关标签:
4条回答
  • 2020-12-08 02:12

    The camera is looking down its internal negative z-axis. So create a vector pointing down the negative z-axis:

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

    Now, apply the same rotation to the vector that is applied to the camera:

    vector.applyQuaternion( camera.quaternion );
    

    You can get the angle in radians to the target like so:

    angle = vector.angleTo( target.position );
    

    EDIT: You can now get the direction in which the camera is looking like so:

    var vector = new THREE.Vector3(); // create once and reuse it!
    ...
    camera.getWorldDirection( vector );
    

    Note: By passing in the vector in which to store the result, the method will not have to instantiate a new THREE.Vector3 every time the method is called.

    Updated to three.js r.107

    0 讨论(0)
  • 2020-12-08 02:12

    I can't comment but fluffybunny's answer works perfectly. getWorldDirection()and then changing that vector to radians is the way to go.

    0 讨论(0)
  • 2020-12-08 02:14

    I spent a long time trying to figure out captain obvious's question.

    This is how it finally worked for me:

        vector = camera.getWorldDirection();
        theta = Math.atan2(vector.x,vector.z);
    

    theta is in radians. This is how I orient my game's character to face the same way the camera is facing. The getWorldDirection() is a fairly new option on camera.

    0 讨论(0)
  • 2020-12-08 02:18

    fluffybunny nailed it. With a small change to his awesome idea, you can get the rotation in degrees:

    var vector = camera.getWorldDirection();
    angle = THREE.Math.radToDeg( Math.atan2(vector.x,vector.z) );  
    
    0 讨论(0)
提交回复
热议问题