[英]Error finding the angle between two points
這個問題很難解釋,因此我將使用圖像來幫助我:
我正在嘗試找到水箱中間與鼠標之間的角度。 橙色點表示鼠標位置,紅色線分隔兩個實例,綠色/石灰線顯示坦克的炮塔角度。 我已經多次檢查堆棧溢出,但仍然沒有找到解決問題的辦法。 我什至用谷歌搜索。 在這兩種方法中,我都發現了許多代碼組來“尋找角度”。 我確信這些方法能奏效,所以我懷疑我的問題出在錯誤的代碼上。 我正在猜測在MouseMotionListener中發現錯誤。
我用來創建偽線(不是綠線或紅線)的兩個點是水箱的中間點new Point(Tank.getX() + 16, Tank.getY() + 16)
(水箱大小是32x32)和鼠標指針(在發生新的鼠標移動事件時設置)。
有關我的程序的詳細信息:
簡而言之,我的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
好吧,經過大量的Google搜索,我發現確實沒有錯誤。 所有的代碼都是正確的,所有..幾乎所有的東西都是正確的。 唯一錯誤的是它偏離了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;
}
由於某種原因,我覺得我由於多次忽略了我而降低了幾分智商。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.