2016-10-14 124 views
0

我通過dispatchGenericMotionEvent(android.view. MotionEvent)方法從我的藍牙手柄控制器接收軸位置。 我的方法:獲取當前的android遊戲手柄軸位置

@Override 
public boolean dispatchGenericMotionEvent(final MotionEvent event) { 
    if(mPadListener==null || 
      (event.getSource()&InputDeviceCompat.SOURCE_JOYSTICK)!=InputDeviceCompat.SOURCE_JOYSTICK){ 
     return super.dispatchGenericMotionEvent(event); 
    } 

    int historySize = event.getHistorySize(); 
    for (int i = 0; i < historySize; i++) { 
     // Process the event at historical position i 
     Log.d("JOYSTICKMOVE",event.getHistoricalAxisValue(MotionEvent.AXIS_Y,i)+" "+event.getHistoricalAxisValue(MotionEvent.AXIS_Z,i)); 
    } 
    // Process current position 
    Log.d("JOYSTICKMOVE",event.getAxisValue(MotionEvent.AXIS_Y)+" "+event.getAxisValue(MotionEvent.AXIS_Z)); 

    return true; 
} 

的問題是,當我釋放所有搖桿軸,我不會在我的日誌越來越最後軸值(0,0)。例如在(0.23,0.11)中停止,並且只有在下一個移動事件之後纔會在logcat中顯示相應的值。更重要的是 - 即使我按下正常按鈕,情況也是一樣的(按鈕事件被其他方法完全捕獲dispatchKeyEvent(android.view.KeyEvent)

發生了什麼事?

回答

0

您得到一個MotionEvent.ACTION_MOVE事件的零位置,但是您收到的值不一定是零。你需要獲得操縱桿的平坦範圍,這給出了我們應該考慮操縱桿靜止的值(即,如果我們低於平坦範圍,那麼我們處於零位)。請參閱getCenteredAxis,它可以修正平坦範圍(https://developer.android.com/training/game-controllers/controller-input.html):

private static float getCenteredAxis(MotionEvent event, 
     InputDevice device, int axis, int historyPos) { 
    final InputDevice.MotionRange range = 
      device.getMotionRange(axis, event.getSource()); 

    // A joystick at rest does not always report an absolute position of 
    // (0,0). Use the getFlat() method to determine the range of values 
    // bounding the joystick axis center. 
    if (range != null) { 
     final float flat = range.getFlat(); 
     final float value = 
       historyPos < 0 ? event.getAxisValue(axis): 
       event.getHistoricalAxisValue(axis, historyPos); 

     // Ignore axis values that are within the 'flat' region of the 
     // joystick axis center. 
     if (Math.abs(value) > flat) { 
      return value; 
     } 
    } 
    return 0; 
}