1

タイトルがわかりにくいと思われる場合は申し訳ありませんが、これが私がやろうとしていることです。

タッチ方向を検出する大きな円形のボタンがあります。次のようなタッチ入力座標の変化のdyとdxからUP/DOWN / LEFT/RIGHTを見つけることができます。

          if(Math.abs(dX) > Math.abs(dY)) {
              if(dX>0) direction = 1; //left
              else direction = 2; //right
          } else {
              if(dY>0) direction = 3; //up
              else direction = 4;   //down
          }

ただし、ボタンを少し回転させることができるため、タッチ方向も調整する必要がある場合に対応したいと思います。たとえば、ボタンを少し左に回転させると、UPは指が真北ではなく、北西に移動するようになります。これをどのように処理しますか?

4

1 に答える 1

2

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
}
于 2012-04-04T20:12:51.587 に答える