Java:计算两点之间的角度(以度为单位)
我需要计算我自己的 Point 类的两点之间的角度(以度为单位),点 a 应为中心点。
方法:
public float getAngle(Point target) {
return (float) Math.toDegrees(Math.atan2(target.x - x, target.y - y));
}
测试 1: // 返回 45
Point a = new Point(0, 0);
System.out.println(a.getAngle(new Point(1, 1)));
测试 2: // 返回 -90,预期:270
Point a = new Point(0, 0);
System.out.println(a.getAngle(new Point(-1, 0)));
如何将返回结果转换为 0 到 359 之间的数字?
I need to calculate the angle in degrees between two points for my own Point class, Point a shall be the center point.
Method:
public float getAngle(Point target) {
return (float) Math.toDegrees(Math.atan2(target.x - x, target.y - y));
}
Test 1: // returns 45
Point a = new Point(0, 0);
System.out.println(a.getAngle(new Point(1, 1)));
Test 2: // returns -90, expected: 270
Point a = new Point(0, 0);
System.out.println(a.getAngle(new Point(-1, 0)));
How can i convert the returned result into a number between 0 and 359?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以添加以下内容:
顺便说一下,为什么您不想在这里使用双精度?
you could add the following:
by the way, why do you want to not use a double here?
我从 johncarls 解决方案开始,但需要调整它以获得我所需要的。
主要是,当角度增加时,我需要它顺时针旋转。我还需要 0 度来指向北。他的解决方案让我很接近,但我决定也发布我的解决方案,以防它对其他人有帮助。
我添加了一些附加注释,以帮助解释我对该函数的理解,以防您需要进行简单的修改。
I started with johncarls solution, but needed to adjust it to get exactly what I needed.
Mainly, I needed it to rotate clockwise when the angle increased. I also needed 0 degrees to point NORTH. His solution got me close, but I decided to post my solution as well in case it helps anyone else.
I've added some additional comments to help explain my understanding of the function in case you need to make simple modifications.
基于萨阿德·艾哈迈德的回答,这是一种可用于任意两点的方法。
Based on Saad Ahmed's answer, here is a method that can be used for any two points.
为什么每个人都把事情复杂化?
唯一的问题是 Math.atan2( x , y)
正确的答案是 Math.atan2( y, x)
他们所做的只是混合 Atan2 的变量顺序,导致它反转旋转程度。
你所要做的就是查找语法
https://www .google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/
Why is everyone complicating this?
The only problem is Math.atan2( x , y)
The corret answer is Math.atan2( y, x)
All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.
All you had to do was look up the syntax
https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/
Math.atan( double) 非常清楚,返回值的范围可以是 -pi/2 到 pi/2。所以你需要补偿该返回值。
The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.
如果您想要从北开始的“方位”度数,那么:
您可以这样做:
If you want the "bearing" degrees from north, so:
you can do this:
现在,将圆形值的方向保持在 0 到 359 之间的角度可以是:
now for orientation of circular values to keep angle between 0 and 359 can be:
我的实现:
输入:
输出为
(以度为单位)。
my realization:
Input:
Output is
in degrees.
怎么样:
What about something like :