Reputation: 21
I am working on a 2D tank game. When I press two arrow keys simultaneously(such as up and right), the tank should go forward and rotate right at the same time. However, when I release one key (For example, I press up and right at the same time then release right but keep pressing up. Theoretically the tank should stop rotating and keep going forward), the tank stops directly. Why?
My code:
getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
onKeyPressed(event);
move();
}
});
getScene().setOnKeyReleased(new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent event){
onKeyReleased(event);
}
});
public void onKeyPressed(KeyEvent event){
switch (event.getCode()){
case LEFT:
isPressLeft=true;
break;
case RIGHT:
isPressRight=true;
break;
case UP:
isPressUp=true;
break;
case DOWN:
isPressDown=true;
break;
}
}
public void move(){
if (isPressUp){
panzer.moveUp();
if (isPressRight){
panzer.rotateRight();
}else if (isPressLeft){
panzer.rotateLeft();
}
}else if (isPressDown){
panzer.moveDown();
if (isPressRight){
panzer.rotateRight();
}else if (isPressLeft){
panzer.rotateLeft();
}
}else if (isPressLeft){
panzer.rotateLeft();
}else if (isPressRight){
panzer.rotateRight();
}
}
public void onKeyReleased(KeyEvent event){
switch (event.getCode()){
case LEFT:
isPressLeft=false;
break;
case RIGHT:
isPressRight=false;
break;
case UP:
isPressUp=false;
break;
case DOWN:
isPressDown=false;
break;
}
}
I have tried the single stepping, when I release the right key, only isPressRight is changed to false. The isPressUp is still true. I think the problem may be in move().
Upvotes: 2
Views: 175
Reputation: 30
That is a sticky keys issue. I've had that before.
Do this.
// In move method
if (!isPressLeft && !isPressRight){} // Set the rotating speed of the player to 0 or whatever you do
if (!isPressUp && !isPressDown){} // Set velocity of the player to 0 or whatever you do.
Upvotes: 1