【问题标题】:Calculating angle between two points - java计算两点之间的角度 - java
【发布时间】:2014-09-27 16:18:21
【问题描述】:

我需要计算两点之间的角度,用一条线与给定的两点相连的固定点。

这是一张说明我需要的图片:

这是我迄今为止尝试过的:

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));
}

说它没有提供正确的答案是没有意义的。

【问题讨论】:

标签: java lines angle points


【解决方案1】:

您可以通过以下方法使用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 类。这只是为了证明它有效。

【讨论】:

  • 为了使其正常工作,我必须添加对结果的更正(在将其转换为度数之后):if (result < 0) result += 360; 否则我的结果会在 ~270 和 ~90 度之间切换(有一个固定点在右下角)。
【解决方案2】:

这是我的 Android 手势库中的代码 sn-p。它可以工作并且已经过全面测试。

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)

【讨论】:

  • 伙计,这实际上是我在 Stack Overflow 中找到的唯一有效答案。所有其他人都不工作!非常感谢!
  • 如何获取x的值
【解决方案3】:

我不知道@user2288580,但即使是简单的测试用例,您的代码也会失败。

firstPoint = (0,0) secondPoint = (0, 5), (5,5), (5,0), (5, -5) (0, -5) (-5, -5), (-5, 0)

请看看这是否适合你@David -

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);
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多