我正在用 Java Swing 制作一個 2D 自上而下的射擊游戲。我想計算滑鼠指標相對于螢屏中心的角度,以便我的一些精靈可以看向指標,這樣我就可以創建由角度和速度描述的射彈。另外,如果指標在螢屏中間的正上方,我希望我的角度為 0°,如果直接向右,則為 90°,如果直接低于 180°,則向左為 270°。
我做了一個函式來計算這個:
public static float calculateMouseToPlayerAngle(float x, float y){
float mouseX = (float) MouseInfo.getPointerInfo().getLocation().getX();
float mouseY = (float)MouseInfo.getPointerInfo().getLocation().getY();
float hypotenuse = (float) Point2D.distance(mouseX, mouseY, x, y);
return (float)(Math.acos(Math.abs(mouseY-y)/hypotenuse)*(180/Math.PI));
}
它背后的想法是我計算斜邊的長度,然后計算所討論的角度的對邊的長度。2 的分數應該是cos我的角度,所以取這個結果arc cos然后乘以 180/Pi 應該會給我以度數為單位的角度。這確實適用于上方和右側,但正下方回傳 0,正下方回傳 90。這意味著我目前有 2 個問題,我的輸出域僅為 [0,90] 而不是 [0,360) 并且它是通過 y(高度)軸鏡像。我哪里搞砸了?
uj5u.com熱心網友回復:
你可以這樣做。
- 對于 的視窗大小
500x500,左上角為點0,0,右下角為500,500。 - 切線是兩點
Y變化的變化。X也稱為斜率,它是特定角度的sin比值cos。要找到該角度,可以使用arctan(Math.atan或)。Math.atan2第二種方法有兩個引數,并在下面使用。
BiFunction<Point2D, Point2D, Double> angle = (c,
m) -> (Math.toDegrees(Math.atan2(c.getY() - m.getY(),
c.getX() - m.getX())) 270)%360;
BiFunction<Point2D, Point2D, Double> distance = (c,
m) -> Math.hypot(c.getY() - m.getY(),
c.getX() - m.getX());
int screenWidth = 500;
int screenHeight = 500;
int ctrY = screenHeight/2;
int ctrX = screenWidth/2;
Point2D center = new Point2D.Double(ctrX,ctrY );
Point2D mouse = new Point2D.Double(ctrX, ctrY-100);
double straightAbove = angle.apply(center, mouse);
System.out.println("StraightAbove: " straightAbove);
mouse = new Point2D.Double(ctrX 100, ctrY);
double straightRight = angle.apply(center, mouse);
System.out.println("StraightRight: " straightRight);
mouse = new Point2D.Double(ctrX, ctrY 100);
double straightBelow = angle.apply(center, mouse);
System.out.println("StraightBelow: " straightBelow);
mouse = new Point2D.Double(ctrX-100, ctrY);
double straightLeft = angle.apply(center, mouse);
System.out.println("Straightleft: " straightLeft);
印刷
StraightAbove: 0.0
StraightRight: 90.0
StraightBelow: 180.0
Straightleft: 270.0
我將弧度輸出從度數轉換Math.atan2為度數。對于您的應用程式,將它們保留為弧度可能更方便。
這是一個類似Function的使用來查找距離Math.hypot
BiFunction<Point2D, Point2D, Double> distance = (c,m) ->
Math.hypot(c.getY() - m.getY(),
c.getX() - m.getX());
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/443877.html
