0

I'm testing a game trying to bind phisical keyboard keys to it. I implemented onKeyUp and onKeyDown to know when the user has pressed a key for move. The problem is that onKeyDown event is getting called repeatedly every 30-40ms.

In theory it must be called only one time if i'm pressing the key without doing onKeyUp, but it is getting called a lot of times until I do keyUp.

What is wrong? this is the code:

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            int factor = GameState.getInstance().getSpaceship().getSpeedFactorCorrespondence();
            int movementRange = sh/factor;
            switch (keyCode) {
            case KeyEvent.KEYCODE_W:
                Log.d("XX_KEYBOARD","onKeyDown KEYCODE_W "+keyCode);
                GameState.getInstance().setJoyY(movementRange);
                return true;
            case KeyEvent.KEYCODE_A:
                Log.d("XX_KEYBOARD","onKeyDown KEYCODE_A "+keyCode);
                GameState.getInstance().setJoyX(-movementRange);
                return true;
            case KeyEvent.KEYCODE_S:
                Log.d("XX_KEYBOARD","onKeyDown KEYCODE_S "+keyCode);
                GameState.getInstance().setJoyY(-movementRange);
                return true;
            case KeyEvent.KEYCODE_D:
                Log.d("XX_KEYBOARD","onKeyDown KEYCODE_D "+keyCode);
                GameState.getInstance().setJoyX(movementRange);
                return true;
            case KeyEvent.KEYCODE_J:
                Log.d("XX_KEYBOARD","onKeyDown KEYCODE_J "+keyCode);
                touchX=sw/2;
                touchY=sh/2;
                LaserManager.getInstance().startLaserThread();
                return true;
            default:
                Log.d("XX_KEYBOARD","onKeyDown default "+keyCode);
                return super.onKeyDown(keyCode, event);
        }
    }
NullPointerException
  • 36,107
  • 79
  • 222
  • 382
  • https://stackoverflow.com/questions/12950215/onkeydown-and-onkeylongpress – Murat Karagöz Aug 06 '17 at 10:37
  • AFAIK it is a normal behavior. This is one of the feature needed inorder to build a drag and drop action when creating a custom view. If you want to create your own `onClick` using this then you need a boolean flag and some sort of logic for checking. – Enzokie Aug 06 '17 at 10:51

0 Answers0