2012-02-05 278 views
1

我正在開發Game Maker類遊戲(不是真正的遊戲製作者),因爲我在真實語言中編寫遊戲失敗(可以編寫普通應用程序,只是不能遊戲)很多次。從x和y速度計算方向角

無論如何,在我使用的方向功能的程序被證明是有時錯誤。然而,物體的x和y速度總是正確的,所以我想計算方向角(以度爲單位)。不幸的是我不是天才的數學,我總是在三角失敗;(你能幫我

我的遊戲製作IDE的角度座標系如下:?

  270 deg. 
    180 deg.  0 deg. 
     90 deg. 

定位系統,就像是大多數環境(0,0在左上角)

回答

9

數學庫通常會與被叫atan2只是用於該目的的功能:

double angle = atan2(y, x); 

的角度以弧度爲單位;乘以180/PI轉換爲度數。角度範圍從-pi到pi。 0角是正x軸,角度順時針增長。如果您需要其他配置,則需要進行較小的更改,如0角度爲負y軸,範圍從0至359.99度。

使用atan2而不是atan或任何其他反轉三角函數的主要原因是,它會爲您計算角度的正確角度,並且不需要一系列if語句。

1

使用反正切函數應該是這樣的:

double direction(double x, double y) { 
    if (x > 0) 
     return atan(y/x); 
    if (x < 0) 
     return atan(y/x)+M_PI; 
    if (y > 0) 
     return M_PI/2; 
    if (y < 0) 
     return -M_PI/2; 
    return 0; // no direction 
} 

(其中x和y是水平和垂直速度,M_PI是pi和ATAN是反正切函數)

0

在遊戲製造商具體情況,你可以使用下列內容:

direction = point_direction(x, y, x+x_speed, y+y_speed) 
speed = point_distance(x, y, x+x_speed, y+y_speed) 

(比較當前和未來的x/y座標和返回值)

相反的過程來獲得X/y_speed:

x_speed = lengthdir_x(speed, direction) 
y_speed = lengthdir_y(speed, direction) 

Note: Added this post because its still viewed in relation to Game Maker: 
Studio and its specific functions. Maybe it has no value for the person who 
asked originally but i hope it will help some Game Maker users who wander here.