这个问题很难解释,所以我用一张图片来帮助我:
我正在尝试找到水箱中部与鼠标之间的角度。橙色点表示鼠标位置,红线分隔两个实例,绿色/石灰线显示坦克的炮塔角度。我已经多次查看堆栈溢出,但没有找到解决问题的方法。我什至用谷歌搜索过。在这两者中,我发现了许多组代码来“寻找角度”。我确信这些有效,所以我怀疑我的问题出在糟糕的代码手中。我猜测错误是在 MouseMotionListener 中发现的。
我用来创建伪线(不是绿线或红线)的两个点是坦克的中点new Point(Tank.getX() + 16, Tank.getY() + 16)
(坦克尺寸为32x32)和鼠标点(当有新的鼠标移动事件时设置)。
有关我的计划的详细信息:
- 创建一个框架并附加一个 MouseMotionListener。
- 已创建 JPanel 并将其添加到框架中。
- 所有内容都绘制在 JPanel 上。
简而言之,我的 getAngle()
代码错误,我的 MouseMotionListener 错误,或者我提供了错误的参数。有什么问题吗?...
编辑:按照评论中的要求,这里是我的代码和输出:
代码:
public static float getAngle(Point source, Point destination) {
System.out.println(source + "\n" + destination);
double xDiff = source.x - destination.x;
double yDiff = source.y - destination.y;
System.out.println((float) Math.toDegrees(Math.atan2(yDiff, xDiff)));
return (float) Math.toDegrees(Math.atan2(yDiff, xDiff));
}
输出:
java.awt.Point[x=116,y=116] // Source point
java.awt.Point[x=134,y=123] // Destination point
-158.7495
最佳答案
好吧,经过大量谷歌搜索后,我发现确实没有错误。所有代码都是正确的,所有......几乎一切都是正确的。唯一的问题是它倾斜了 90 度。这个想法曾多次在我脑海中闪过,但每次我看着点和线,它似乎都不正确......固定代码如下:
public static float getAngle(Point source, Point destination) {
System.out.println(source + "\n" + destination);
double xDiff = source.x - destination.x;
double yDiff = source.y - destination.y;
System.out.println((float) Math.toDegrees(Math.atan2(yDiff, xDiff)));
return (float) Math.toDegrees(Math.atan2(yDiff, xDiff)) + 90.0F;
}
出于某种原因,我觉得我因为多次忽视这一点而失去了几个智商点。
关于java - 查找两点之间的角度时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876094/