Z
Z
zevilcube2019-08-28 00:51:48
Java
zevilcube, 2019-08-28 00:51:48

How in Java to make sure that the keyPressed of one key does not interrupt the keyPressed of another?

Some parts of the code have been omitted for brevity.
I have a JFrame for a future game. I add KeyListener to it: Class with KeyListener:
window.addKeyListener(new KeyListener_WASD());

public class KeyListener_WASD implements KeyListener {
    private int horizontal = 0; //переменная "на сколько нужно передвинуть объект горизонтально"
    private int vertical = 0; //переменная "на сколько нужно передвинуть объект вертикально", пока что не используется.
    private HashMap <Integer, Boolean> pba = new HashMap <> (); // int - код клавиши, bool - нажата ли она

    KeyListener_WASD () {
        pba.put(KeyEvent.VK_W, false);
        pba.put(KeyEvent.VK_A, false);
        pba.put(KeyEvent.VK_S, false);
        pba.put(KeyEvent.VK_D, false);
        pba.put(KeyEvent.VK_SPACE, false);
    }

    public void keyPressed(KeyEvent e) {
        GameObject movingObject = Game.getCurrentMap().getObjects().get(0);
        pba.put(e.getKeyCode(), true);

        if (pba.get(KeyEvent.VK_A)) {
            horizontal = -movingObject.speed;
        }
        if (pba.get(KeyEvent.VK_D)) {
            horizontal = movingObject.speed;
        }

        if (pba.get(KeyEvent.VK_SPACE)) {
            movingObject.jump();
        }

        movingObject.move(horizontal, vertical);
    }
    public void keyReleased(KeyEvent e) {
        pba.put(e.getKeyCode(), false);

        if (e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_D) {
            horizontal = 0;
        }
    }
    public void keyTyped(KeyEvent e) {
    }
}

Actually, what is the problem:
When you hold A or D, the object from the game map should move to the left or right, respectively. BUT! If, while one of these keys is pressed, any other key is pressed, the object stops moving. At all.
It seems to me that keyPressed (or maybe keyReleased), triggered by one key, interrupts the action of keyPressed by another key.
How can I solve the problem? Help me please.
PS Perhaps there is a govnokoda or I incorrectly state the idea.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question