计算两点之间的角度-Java [英] Calculating angle between two points - java
问题描述
我需要计算两个点之间的角度(以度为单位),固定点通过一条线与给定的两个点连接.
I need to calculate the angle in degrees between two points, with a fixed point that is connected with the given two points by a line.
这是一张说明我需要的图片:
Here is an image that illustrates what I need:
这是我到目前为止尝试过的:
Here is what I have tried so far:
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));
}
说没有提供正确答案是毫无意义的.
It's pointless to say that it doesn't provide the correct answer.
推荐答案
您可以使用以下方法,使用Math.atan2
方法以弧度为单位计算角度:
You can have the following method that calculates the angle in radians using the Math.atan2
method:
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
将生成的角度从弧度转换为度):
And call it with three points (using Math.toDregrees
to transform resulting angle from radians to degrees):
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的标准Point
或Line2D
类.这只是为了演示它的工作原理.
Feel free to use Java's standard Point
or Line2D
classes in your solution though. This was just to demonstrate it works.
这篇关于计算两点之间的角度-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!