Search code examples
javascriptvectortrigonometryangleeuler-angles

How to convert a vector to a euler angle


I've scoured the net for almost three hours in an attempt to find the answer to my question. I have read articles and watched many videos that show how to get a vector's angle in degrees or radians. But that is not exactly what I'm looking for.

I suspect I may not know the correct words to describe what I'm trying to do, so I decided to draw it. enter image description here

In essence, I'm trying to write a simple function that takes a 2D vector as input ([3,1] in my example) and returns what I think is called a euler angle. In my example the output would be around 290. The vector could have negative coordinates, for instance [-3, -1] would output around 110.

I don't know if this changes anything but negative outputs are also acceptable. For instance, instead of 270, -90 would be a corresponding acceptable output.


Solution

  • Since the angle from x-axis counterclockwise is invert tangent of y/x you just need to have result in degrees, increase it by 270 keeping angles domain in [0,360) like that:

    function euler_angle(x,y) { 
        var rad = Math.atan(y/x);   // arcus tangent in radians
        var deg = rad*180/Math.PI;  // converted to degrees
        if (x<0) deg += 180;        // fixed mirrored angle of arctan
        var eul = (270+deg)%360;    // folded to [0,360) domain
        return eul;
    }