Calculating the angle between two lines without having to calculate the slope? (Java)

后端 未结 8 1221
夕颜
夕颜 2020-11-28 07:27

I have two Lines: L1 and L2. I want to calculate the angle between the two lines. L1 has points: {(x1, y1), (x2, y2)} and L2 has points: {(x3, y3), (x4, y

8条回答
  •  难免孤独
    2020-11-28 07:37

    The atan2 function eases the pain of dealing with atan.

    It is declared as double atan2(double y, double x) and converts rectangular coordinates (x,y) to the angle theta from the polar coordinates (r,theta)

    So I'd rewrite your code as

    public static double angleBetween2Lines(Line2D line1, Line2D line2)
    {
        double angle1 = Math.atan2(line1.getY1() - line1.getY2(),
                                   line1.getX1() - line1.getX2());
        double angle2 = Math.atan2(line2.getY1() - line2.getY2(),
                                   line2.getX1() - line2.getX2());
        return angle1-angle2;
    }
    

提交回复
热议问题