Search code examples
javakeyboard-events

Multiple Keyboard Inputs Java


Im working on a space invaders type game and I have a keyboard controller class but the problem is if I want to move my player I can shoot at the same time, how can I change my controller to fix this?

Key Pressed

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();

    for(int i = 0; i<handler.object.size(); i++) {
        gameObject tempObject = handler.object.get(i);

        if(tempObject.getId()==ObjectID.Player){
            if(key == KeyEvent.VK_D) tempObject.setVelX(5);
            if(key == KeyEvent.VK_A) tempObject.setVelX(-5);
            if(key == KeyEvent.VK_W) tempObject.setVelY(-10);
            if(key == KeyEvent.VK_S) tempObject.setVelY(10);
        }
        if(tempObject.getId()==ObjectID.Player && key == KeyEvent.VK_SPACE){
            CurrentTime = System.currentTimeMillis();

            if(NextShootTime<CurrentTime){
                handler.addObject(new Bullet(tempObject.getX()+40, tempObject.getY()-20,0, ObjectID.Bullet));
                handler.addObject(new Bullet(tempObject.getX()+30, tempObject.getY()-20,1, ObjectID.Bullet));
                handler.addObject(new Bullet(tempObject.getX()+50, tempObject.getY()-20,2, ObjectID.Bullet));
                NextShootTime = CurrentTime+ShootDelay;
            }
        }

        if(tempObject.getId()==ObjectID.Bullet){
            tempObject.setVelY(-5f);
            if(key == KeyEvent.VK_K) {
                handler.removeObject(tempObject);
            }
        }
    }

    if(key == KeyEvent.VK_ESCAPE ) {
        System.exit(0);
    }
}

Key Released

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

    for(int i = 0; i<handler.object.size(); i++) {
        gameObject tempObject = handler.object.get(i);

        if(tempObject.getId()==ObjectID.Player){
            if(key == KeyEvent.VK_D) tempObject.setVelX(0);
            if(key == KeyEvent.VK_A) tempObject.setVelX(0);
            if(key ==KeyEvent.VK_W) tempObject.setVelY(0);
            if(key ==KeyEvent.VK_S) tempObject.setVelY(0);
        }
    }
}

Solution

  • Do not calculate the speed, acceleration and direction in the KeyEvent. You should do that in your GameLoop. You can memorize the keystrokes in the KeyEvent and then process them in the GameLoop.

    You could query the KeyEvents as follows.

    private final BitSet keys = new BitSet();
    
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            keys.set(e.getKeyCode());
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
             keys.clear(e.getKeyCode());
        }
    });
    

    In your GameLoop you can use keys.get(keyCode) to query whether one or more keys are pressed.