Answer the question
In order to leave comments, you need to log in
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) {
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question