Two key's Pressed at the same time
hi,
I wanna test for two buttons pressed at the same time, but it just wont happen!!
I am using this code:
publicvoid keyPressed(KeyEvent e){
if (e.getKeyCode() == e.VK_X && e.getKeyCode() == e.VK_RIGHT){
System.out.println("Its working...");
doWhatEver();
}
}
is this the right code to do so, or is it completly wrong?
You can only get one key at a time, you need a boolean value for each key.
By example:
private boolean upPressed;
private boolean downPressed;
private boolean leftPressed;
private boolean rightPressed;
.................
private class KeyAction extends KeyAdapter {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
upPressed = true;
break;
case KeyEvent.VK_DOWN:
downPressed = true;
break;
case KeyEvent.VK_LEFT:
leftPressed = true;
break;
case KeyEvent.VK_RIGHT:
rightPressed = true;
break;
}
if (upPressed && leftPressed) {
System.out.println("North-East");
} else if (upPressed && rightPressed) {
System.out.println("North-West");
} else if (downPressed && leftPressed) {
System.out.println("South-East");
} else if (downPressed && rightPressed) {
System.out.println("South-West");
}
}
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
upPressed = false;
break;
case KeyEvent.VK_DOWN:
downPressed = false;
break;
case KeyEvent.VK_LEFT:
leftPressed = false;
break;
case KeyEvent.VK_RIGHT:
rightPressed = false;
break;
}
//Do whatever here
}
}
}
Just use the keylistener stuff with the booleans and then poll the boolean's in your game loop:
if (upPressed && rightPressed) {
System.out.println("Its working...");
doWhatEver();
}
jpw35a at 2007-7-14 20:57:42 >

i mean, would it be better to use a seperate class to handle all key events, or should I stick to implementing the keyListener class?Which is better, faster...etc?