0

I have a 2 player game, one player uses WASD, one uses the arrows keys. I can't figure out how to allow multiple keys at once. Here's my code:

List keyArray = new ArrayList();

    // Red guy input.
    if (e.getKeyCode() == 37) { // left key

        new LoadRedCharacter("leftrightfootred.gif");

        int x = Frame.redCharacterLabel.getX();
        int y = Frame.redCharacterLabel.getY();
        if (x < 0) {
            Frame.redHealthLabel.setLocation(x - 13, y - 15);
            Frame.redCharacterLabel.setLocation(x + 1, y);
            ResetEntities.redCharacterObj.setLocation(x + 1, y);
        } else {
            Frame.redHealthLabel.setLocation(x - 13, y - 15);
            Frame.redCharacterLabel.setLocation(x - 2, y);
            ResetEntities.redCharacterObj.setLocation(x - 2, y);
        }
        keyArray.add(37);
        System.out.println("array" + keyArray);
        Frame.frame.repaint();
        checkHitBox();
    }

I also have code for the blue characters left movement. Then I have this:

        // Multi key input
    if (keyArray.contains(37) && keyArray.contains(65)) {
        System.out.print("array contains 37 and 65");
    }

In order to test it. However it doesn't work ..

Nic
  • 98
  • 2
  • 11
  • 1
    Look at similar post http://stackoverflow.com/questions/2623995/swings-keylistener-and-multiple-keys-pressed-at-the-same-time – Arsen Alexanyan Mar 12 '13 at 12:57

1 Answers1

0

You could take a multi-threaded approach. Have one thread that only cares about the red keys and another that only cares about the blue. They each act independantly and should not interfere with each other if you use synchronization on shared variables.

David K
  • 1,296
  • 18
  • 39