2014-09-27 1093 views
9

我需要计算两点之间的角度度数,用一个固定点与给定的两点连线。计算两点之间的夹角 - java

这里是一个形象,说明了什么,我需要:

enter image description here

这里是我到目前为止已经试过:

public static float GetAngleOfLineBetweenTwoPoints(float x1, float x2, float y1, float y2) { 
     float xDiff = x2 - x1; 
     float yDiff = y2 - y1; 
     return (float) (Math.atan2(yDiff, xDiff) * (180/Math.PI)); 
} 

这是毫无意义地说,它不提供正确答案。

+0

你甚至不考虑“原产地”点的坐标目前,对不对? – qqilihq 2014-09-27 16:20:31

+2

你的定点是什么?你还需要那个点 – 2014-09-27 16:20:32

+0

加第三点(如@getlost提到)并使用矢量角公式:http://www.vitutor.com/geometry/vec/angle_vectors.html – maskacovnik 2014-09-27 16:22:36

回答

13

可以有以下的方法,其计算在利用Math.atan2方法弧度的角度:

public static double angleBetweenTwoPointsWithFixedPoint(double point1X, double point1Y, 
     double point2X, double point2Y, 
     double fixedX, double fixedY) { 

    double angle1 = Math.atan2(point1Y - fixedY, point1X - fixedX); 
    double angle2 = Math.atan2(point2Y - fixedY, point2X - fixedX); 

    return angle1 - angle2; 
} 

并与三点称之为(使用Math.toDregrees变换所得从弧度到度角):

System.out.println(Math.toDegrees(
      angleBetweenTwoPointsWithFixedPoint(0, 0, // point 1's x and y 
               1, 1, // point 2 
               1, 0 // fixed point 
               ))); 

输出:90.0

随意使用Java的标准PointLine2D类在您的解决方案,但。这只是为了证明它的工作原理。

6

这是我的Android手势库的代码片段。它的工作原理并经过充分测试。

public double getAngleFromPoint(Point firstPoint, Point secondPoint) { 

    if((secondPoint.x > firstPoint.x)) {//above 0 to 180 degrees 

     return (Math.atan2((secondPoint.x - firstPoint.x), (firstPoint.y - secondPoint.y)) * 180/Math.PI); 

    } 
    else if((secondPoint.x < firstPoint.x)) {//above 180 degrees to 360/0 

     return 360 - (Math.atan2((firstPoint.x - secondPoint.x), (firstPoint.y - secondPoint.y)) * 180/Math.PI); 

    }//End if((secondPoint.x > firstPoint.x) && (secondPoint.y <= firstPoint.y)) 

    return Math.atan2(0 ,0); 

}//End public float getAngleFromPoint(Point firstPoint, Point secondPoint) 
+0

男人,这实际上是只有在Stack Overflow中找到的有效答案。所有其他人都不工作!非常感谢! – DccBr 2016-05-23 04:18:02

+0

我怎样才能得到'x'的值 – 2017-04-19 08:48:48

1

我不知道@ user2288580,但即使是简单的测试用例,代码也会失败。 (0,0) secondPoint =(0,5),(5,5),(5,0),(5,-5)(0,-5)( - 5,-5 ),(-5,0)

请看看这对你的作品@大卫 -

public double angleBetween2CartesianPoints(double firstX, double firstY, double secondX, double secondY) { 
    double angle = Math.atan2((secondX - firstX), (secondY - firstY)) * 180/Math.PI; 
    if (angle < 0) { 
     return (360 + angle); 
    } else { 
     return (angle); 
    } 
}