2014-09-27 1098 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); 
    } 
}