2014-09-27 7 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

+2

당신의 고정 점은 무엇입니까? –

+0

점 (@getlost 언급)을 추가하고 벡터 각도 공식을 사용하십시오 : http://www.vitutor.com/geometry/vec/angle_vectors.html – maskacovnik

답변

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 사용) 3 점을 호출

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

출력 : 90.0

자바의 표준 Point 또는를 자유롭게 사용귀하의 솔루션에 클래스. 이것은 단지 그것을 증명하는 것이 었습니다.

6

다음은 Android Gesture 라이브러리의 코드 스 니펫입니다. 작동하며 완전히 테스트되었습니다.

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

남자, 이것은 실제로 스택 오버플로에서 발견 된 유일한 유효한 대답. 다른 모든 사람들은 작동하지 않습니다! 고마워요! – DccBr

+0

어떻게'x'의 값을 얻을 수 있습니까? –

1

@ user2288580 잘 모르겠지만 단순한 테스트 케이스의 경우에도 코드가 실패합니다.

firstPoint = (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); 
    } 
}