Recognizing two keyboard inputs at the same time

Hi and sorry for my bad english first.
I’m creating a multiplayer-mode for my little pong game at the moment, but when both players try to move their “character”, only one of them reacts.
my pretty simple code:

void draw ()
{
  background(0);
  
  strokeWeight(playerspeed);
  stroke(255);
  strokeCap(SQUARE);
  line(width/2,3*playerspeed,width/2,height-3*playerspeed);
  
  rect(xPosP1 , yPosP1 , playerWidth , playerHeight);
  rect(xPosP2 , yPosP2 , playerWidth , playerHeight);
  rect(xBall , yBall , ballWidth , ballHeight);
  player1();
  player2();
  
}


void player1 ()
{
  
  if (keyPressed)
  {
    if (key == 'w' || key == 'W')
    {
      yPosP1 -= playerspeed;
    } else if (key == 's' || key == 'S')
    {
      yPosP1 += playerspeed;
    }
  }

  if (yPosP1 < playerHeight/2)
  {
    yPosP1 = playerHeight/2;
  } else if (yPosP1 > height - (playerHeight/2))
  {
    yPosP1 = height - (playerHeight/2);
  }

}

void player2 ()
{
   if (keyPressed)
  {
    if (key == 'k' || key == 'K')
    {
      yPosP2 -= playerspeed;
    } else if (key == 'm' || key == 'M')
    {
      yPosP2 += playerspeed;
    }
  }

  if (yPosP2 < playerHeight/2)
  {
    yPosP2 = playerHeight/2;
  } else if (yPosP2 > height - (playerHeight/2))
  {
    yPosP2 = height - (playerHeight/2);
  }
  
}

How can I make Processing react to both inputs at the same time?
By the way, I’m an absolute beginner.
Can anyone help me?
Thanks in advance. :smiley:

The problem is that key only tracks the last key that was pressed. So with two players, they can’t both be pressing the last key!

You will need to restructure your code so that you are keeping track of which keys are held down. You can do this by making use of the keypressed() and keyReleased() functions:

char[] tracked_keys = ['w','s','k','m']
boolean[] key_down = { false, false, false, false };

void keyPressed(){
  keyTrack(true);
}

void keyReleased(){
  keyTrack(false);
}

void keyTrack(boolean b);
  for( int i = 0; i < tracked_keys.length; i++){
    if( key == tracked_keys[i] ){
      key_down[i] = b;
    }
  }
}

// if( key_down[0] ){ // 'w' is pressed
1 Like

Thank you! It works! :slight_smile: