使用Math.atan2(DY,DX)擺脫的水平正的角度逆時針座標以弧度
double pressed = Math.atan2(dY, dX);
從這個角度減去的旋轉量(以弧度表示逆時針旋轉量) ,把角到按鈕
pressed -= buttonRotation;
,或者如果你有你的度的角度,轉換的座標系統使其弧度
pressed -= Math.toRadians(buttonRotation);
然後你可以從這個角度
int dir = (int)(Math.round(2.0d*pressed/Math.PI) % 4);
計算更簡單的方向數這給正確0,上漲1,左2,下3.我們需要在角度爲負糾正的情況下,作爲模數結果也是負的。
if (dir < 0) {
dir += 4;
}
現在假設這些數字是不好的,你不想使用它們,你可以打開,結果,返回任何你喜歡的每一個方向。 把這一切放在一起:
/**
* @param dY
* The y difference between the touch position and the button
* @param dX
* The x difference between the touch position and the button
* @param buttonRotationDegrees
* The anticlockwise button rotation offset in degrees
* @return
* The direction number
* 1 = left, 2 = right, 3 = up, 4 = down, 0 = error
*/
public static int getAngle(int dY, int dX, double buttonRotationDegrees)
{
double pressed = Math.atan2(dY, dX);
pressed -= Math.toRadians(buttonRotationDegrees);
// right = 0, up = 1, left = 2, down = 3
int dir = (int)(Math.round(2.0d*pressed/Math.PI) % 4);
// Correct negative angles
if (dir < 0) {
dir += 4;
}
switch (dir) {
case 0:
return 2; // right
case 1:
return 3; // up
case 2:
return 1; // left;
case 3:
return 4; // down
}
return 0; // Something bad happened
}
謝謝馬特,我認爲這正是我需要的。真棒回答! – MikeT 2012-04-04 21:59:29