AaronC
AaronC

Reputation: 1

Accepting 2 keyboard inputs at once using KeyListener

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == 32){ //spacekey
        if (menu.isRun == true){ //Checks if menu is active or not
            if (framecount > 10){ //Prevents too many missiles
                instance.player.spaceKeyPressed();
                framecount = 0;
            }
        }
        menu.isRun = true; //sets menu to inactive
        if (toggle != true){//prevents reopening game after a game over
            if (menu.spaceKeyPressed()){
                instance.CanRun = true; //loads game
                toggle = true;
                menu.update();//updates menu
            }
        }
    }
    if (e.getKeyCode() == 39) instance.player.rightKeyPressed();//right key moves player right
    if (e.getKeyCode() == 37) instance.player.leftKeyPressed(); //left key moves player left
}

With this the user can only move or shoot, not both at once. For example if the user is holding right arrow to move right and presses space the user will stop.

Upvotes: 0

Views: 99

Answers (2)

jaroslawjanas
jaroslawjanas

Reputation: 111

boolean keyA=false;
boolean keyD=false;

//    keys
@Override
public void keyPressed(KeyEvent e) {
    int key= e.getKeyCode();

    if(key==KeyEvent.VK_A){
        keyA=true;
    }

    if(key==KeyEvent.VK_D){
        keyD=true;
    }
}

@Override
public void keyReleased(KeyEvent e) {
    int key= e.getKeyCode();

    if(key==KeyEvent.VK_A){
        keyA=false;
    }

    if(key==KeyEvent.VK_D){
        keyD=false;
    }

//In constructor
new Thread(()->{
    while(true){
        try{Thread.sleep(10);}
        catch (InterruptedException e){}

        if(keyA)
            player.moveLeft();
        if(keyD)
            player.moveRight();
    }
}).start();

Notice the usage of KeyEvent.VK_A, makes life much simpler. Also, make sure you have sleep() in your thread, because if it's just while(true) nothing in the loop will execute.

Upvotes: 0

Kars
Kars

Reputation: 917

Use a Class-level attribute collection to determine which other keys are pressed. You will have to implement logic for more than one key being pressed in the keyPressed function that iterates the list. Also remove the key from the list in the keyReleased function.

Upvotes: 1

Related Questions