2012-04-04 79 views
1

對不起標題聽起來有點混亂 - 但是這就是我想要做的事:Android的觸摸方向西北,東北爲UP方向,如果

我有一個大的圓形按鈕上,我發現觸摸方向。我能找到向上/下/左/右在觸摸輸入的變化的DY和DX座標如下:

  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現在是手指向西北移動,而不是純粹的北移。我該如何處理?

回答

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 
} 
+0

謝謝馬特,我認爲這正是我需要的。真棒回答! – MikeT 2012-04-04 21:59:29