How to calculate the angle of a vector from the vertical?

后端 未结 9 1344
感情败类
感情败类 2020-12-15 10:15

Im trying to find out the angle (in degrees) between two 2D vectors. I know I need to use trig but I\'m not too good with it. This is what I\'m trying to work out (the Y axi

9条回答
  •  悲哀的现实
    2020-12-15 10:53

    It looks like Niall figured it out, but I'll finish my explanation, anyways. In addition to explaining why the solution works, my solution has two advantages:

    • Potential division by zero within atan2() is avoided
    • Return value is always positive in the range 0 to 360 degrees

    atan2() returns the counter-clockwise angle relative to the positive X axis. Niall was looking for the clockwise angle relative to the positive Y axis (between the vector formed by the two points and the positve Y axis).

    The following function is adapted from my asteroids game where I wanted to calculate the direction a ship/velocity vector was "pointing:"

    // Calculate angle between vector from (x1,y1) to (x2,y2) & +Y axis in degrees.
    // Essentially gives a compass reading, where N is 0 degrees and E is 90 degrees.
    
    double bearing(double x1, double y1, double x2, double y2)
    {
        // x and y args to atan2() swapped to rotate resulting angle 90 degrees
        // (Thus angle in respect to +Y axis instead of +X axis)
        double angle = Math.toDegrees(atan2(x1 - x2, y2 - y1));
    
        // Ensure result is in interval [0, 360)
        // Subtract because positive degree angles go clockwise
        return (360 - angle) %  360;
    }
    

提交回复
热议问题