所以我正在用 Java 開發一個游戲,我試圖向游標位置發射子彈 - 射擊部分是可以的,但是作為游標和玩家之間的角度(玩家射擊子彈基本上是子彈的第一個坐標) 接近 90 (或 -90) 子彈速度超快,我不知道為什么
紅色區域為超速區域
代碼:
public void run() {
super.run();
final double currentY=y;
final double currentX=x;
double slope = (cursorPos.y - currentY) / (cursorPos.x - currentX);
double angle= Math.toDegrees(Math.atan2(cursorPos.y - currentY, cursorPos.x - currentX));
System.out.println(angle);
while (true){
try {
double newY;// y = m * (x-x.) y.
newY = ((slope*(x - currentX)) currentY);
y= (int) newY;
if ((angle <=-90 && angle>=-180) || (angle >=90 && angle<=180) )
{
x--;
}
else {
x ;
}
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
uj5u.com熱心網友回復:
您按固定增量 1 及時步進 x。所以當專案符號線接近垂直時,斜率 m 是一個很大的數字,它們在 y 中每步覆寫 m 個像素。越接近垂直,它們走得越快。
相反,您需要沿著專案符號所在的線段以固定的距離增量步進。如果端點是 (x0,y0) 和 (x1,y1),則在方程 x = t*(x1-x0) x0 中將 t 從 0 變為 1;y=t*(y1-y0) y0 將掃描線段。要以 1 像素為單位進行掃描,您需要知道沿線有多少像素。那是 L = sqrt(sqr(x1-x0) sqr(y1-y0)),所以對于 i = 0 到 L,t 的值為 i / L。
您需要使用浮點數進行這些計算。
另一個注意事項是,您最終可能會在使用 Sleep 時遇到問題。這可以防止 Swing 事件處理回圈在等待時執行任何作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372477.html
