KeyEvent: Combine Multiple Inputs

Check this code:

public void keyPressed(KeyEvent e)
{
    if (e.getKeyCode() == KeyEvent.VK_W)
    {
        new panel().player1.playerMoves("North", 10, 600,500);
    }
    else if (e.getKeyCode() == KeyEvent.VK_S)
    {
        new panel().player1.playerMoves("South", 10, 600,500);
    }

    if (e.getKeyCode() == KeyEvent.VK_UP)
    {
        new panel().player2.playerMoves("North", 10, 600,500);
    }
    else if (e.getKeyCode() == KeyEvent.VK_DOWN)
    {
        new panel().player2.playerMoves("South", 10, 600,500);
    }
}

      

I have no problem whatsoever with this and my problem does not require knowledge of the class I am calling. What happens is that there are two players. Player1 has controls mapped to the wasd keys and player2 to the arrow keys. However, it seems that these if statements are each other's correspondence. I mean if player1 moves up and player2 starts moving down, player1 should stop. I thought about this using multiple threads, but I wasn't sure if it worked or if there is an easier solution to the problem. Is there anything I can do to make multiple keystrokes work together?

+3


source to share


1 answer


You can save which keys were pressed in any list, name it pressedKeys

. When a key is pressed, you add that key to pressedKeys

. When a key is released (overrides a method keyReleased()

), you remove that key from pressedKeys

. Then you can move the player based on keystrokes. For example,

    public void movePlayer() {
        if ( pressedKeys.contains( UP ) ) {
            movePlayerUp();
        }
        if ( pressedKeys.contains( DOWN ) ) {
            movePlayerDown();
        }
        if ( pressedKeys.contains( S ) ) {
            movePlayerDown();
        }

        ...

    }

      



Required class:

class MyListener implements KeyListener {

    private ArrayList< Integer > keysPressed = new ArrayList< Integer >();

    public MyListener() {

    }

    @Override
    public void keyPressed( KeyEvent e ) {
        if ( !keysPressed.contains( e.getKeyCode() ) ) {
            keysPressed.add( e.getKeyCode() );
        }

        movePlayer();
    }

    @Override
    public void keyReleased( KeyEvent e ) {
        keysPressed.remove( e.getKeyCode() );
    }

    public void movePlayer() {
        //move player based on what keys are pressed.
    }
}

      

+1


source







All Articles