handle multiple key presses ignoring repeated key

后端 未结 3 893
-上瘾入骨i
-上瘾入骨i 2020-12-07 00:17

I had asked this in the comments section of another question (> How do I handle simultaneous key presses in Java?), and was asked to make a new question altogether.

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 00:27

    Your obseravtion that things are handled slowly most likely is caused solely be the many System.out.println() statements.

    Your problem that you do not get diagonal movement stems from your somewhat faulty checking logic - instead of explicitly checking if (for example) keys A and B are pressed, just check them independently - key A moves the character in one direction, B in another. In total (e.g.), by moving WEST and NORTH you will have effectively moved NORTHWEST.

    Instead of a list of pressed keys, you could use a java.util.BitSet and just set the bit for each key that is currently pressed. That should also drastically reduce the amount of code you need to write (keyPressed just sets the bit indicated by key code, keyReleased clears it). To check if a key is pressed you ask the BitSet then if the bit for the code is currently set.

    EDIT: Example of using BitSet instead of a list

    public class BitKeys implements KeyListener {
    
        private BitSet keyBits = new BitSet(256);
    
        @Override
        public void keyPressed(final KeyEvent event) {
            int keyCode = event.getKeyCode();
            keyBits.set(keyCode);
        }
    
        @Override
        public void keyReleased(final KeyEvent event) {
            int keyCode = event.getKeyCode();
            keyBits.clear(keyCode);
        }
    
        @Override
        public void keyTyped(final KeyEvent event) {
            // don't care
        }
    
        public boolean isKeyPressed(final int keyCode) {
            return keyBits.get(keyCode);
        }
    
    }
    

    I made the example implement KeyListener, so you could even use it as is. When you need to know if a key is pressed just use isKeyPressed(). You need to decide if you prefer with raw key code (like I did) or go with key character (like you currently do). In any case, you see how using the BitSet class the amount of code for recording the keys reduces to a few lines :)

提交回复
热议问题