Problem with multiple inputs

Hello,
i’m actually trying to code a litlle, i’m at the beginning and i’m trying to do the character movement, i searched some codes to handle multiple inputs, but i have a problem that i cannot understand :

void keyPressed()
{
  setMove(keyCode, true);
}

void keyReleased()
{
  setMove(keyCode, false);
}

boolean setMove(int k, boolean b)
{
  switch(k) {
    case UP: 
      return isUp = b;
    case DOWN: 
      return isDown = b;
    case LEFT: 
      return isLeft = b;
    case RIGHT: 
      return isRight = b; 
    default:            
      return b;
    }
}

void input() 
{
  if(isUp) {
    test = -1;
    vertical = test;
  }
  else {
    test = 0;
    vertical = test;
  }
  
  if(isDown) {
    vertical = 1;
  }
  else {
    vertical = 0;
  }
  
  if(isLeft) {
    horizontal = -1;
  }
  else {
    horizontal = 0;
  }
  
  if(isRight) {
    horizontal = 1;
  }
  else {
    horizontal = 0;
  }
}

I hope the code isn’t too long, the problem is that it doesn’t move up and left, but it perfectly move down and right.
I tried to remove the down and right condition and it worked perfectly for up and left.
I don’t understand why the vertical variable doesn’t change when there are all conditions together.

Sorry if you don’t understand my problem, my english is not very good.

In switch case you need a break; after each section

You need to be aware that isUp needs to antagonize w/ isDown.

Same for isLeft needs to exclude isRight and vice-versa.

You can do that more succinctly by subtracting isDown w/ isUp:
vertical = int(isDown) - int(isUp);

Same logic for isRight & isLeft:
horizontal = int(isRight) - int(isLeft);

Here’s an online sketch using that subtraction approach for movement inside method Player::move():

1 Like

Oh, my comment was wrong

Gosh.