0

dispatchGenericMotionEvent(android.view. MotionEvent)我在方法中从我的蓝牙游戏手柄控制器接收轴位置。我的方法:

    @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)

这是怎么回事 ?

4

1 回答 1

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;
}
于 2016-12-02T20:32:08.593 回答