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
}