使用Math.atan2(DY、DX)はラジアンで座標の正の水平方向からの角度反時計を取得する
double pressed = Math.atan2(dY, dX);
この角度からの回転量(ラジアン反時計回り回転量)を差し引きます、ボタン
pressed -= buttonRotation;
か、度であなたの角度を持っている場合は、ラジアン
に変換する座標系に角度を置きます
pressed -= Math.toRadians(buttonRotation);
あなたはその後、これは最大1、右0を与える
この角度から
int dir = (int)(Math.round(2.0d*pressed/Math.PI) % 4);
を簡単に方向数を計算することができ、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