i programming the control for a very simple game in a KeyListener. Ive got the Following Problem.
I did something like this(only an easy example not my implemented code):
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
Methodxyz(leftpressed,rightpressed,uppressed)
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
Methodxyz(leftpressed,rightpressed,uppressed)
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = true;
Methodxyz(leftpressed,rightpressed,uppressed)
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = false;
}
}
If i press 2 keys(left,up) at the same time youre able to move the charachter diagonal. The thing is the listener works with the last pressed KeyEvent so if i press left then up, but didnt release the left and release up, the object wont be move(left is still pressed).
How can i handle that? Is it possible to fire keypressed events in my keypressed method of my keylistener til leftpressed is false?
Any ideas?
thanks in advance
解决方案
Don't call the movement method inside the keypress method, instead whenever you call the updates in your gameloop also call an update method in your inputlistener that checks which keys have been pressed, this will allow you to have multiple keypresses at the same time, keypresses that will be set to false once the key is released, like so:
In your inputhandler:
public void update() {
if (up == true) {
SomeMethod(Key.UP);
}
if (down == true) {
SomeMethod(Key.DOWN);
}
if (left == true) {
someMethod(Key.LEFT);
}
if (right == true) {
someMethod(Key.RIGHT);
}
}
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_S:
down = false;
break;
case KeyEvent.VK_W:
up = false;
break;
case KeyEvent.VK_A:
left = false;
break;
case KeyEvent.VK_D:
right = false;
break;
}
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_S:
down = true;
break;
case KeyEvent.VK_W:
up = true;
break;
case KeyEvent.VK_A:
left = true;
break;
case KeyEvent.VK_D:
right = true;
break;