Check out 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'm not having any issues with it and my problem does not require knowledge of the class that I am calling. What is happening is that there are two players. Player1 has the controls bound to the wasd keys and player2 to the arrow keys. However it seems that these if statements are sort of overwriting eachother. What I mean is that if player1 is moving up and player2 starts moving down, player1 will have to stop. I was thinking of solving this using multiple threads, but I wasn't sure if it work work or if there is a simpler solution to the problem. Is there anything I can do to make multiple keystrokes work together?
You can store what keys have been pressed in some list, call it pressedKeys. When a key is pressed, you add that key to pressedKeys. When a key is released (override the keyReleased() method), you remove that key from pressedKeys. Then, you can move the player based on what's in pressed keys. For example,
public void movePlayer() {
if ( pressedKeys.contains( UP ) ) {
movePlayerUp();
}
if ( pressedKeys.contains( DOWN ) ) {
movePlayerDown();
}
if ( pressedKeys.contains( S ) ) {
movePlayerDown();
}
...
}
The desired 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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With