Detecting multiple key inputs for animations

Hey there,

so i am currently implementing animations for my main character.

The goals is to to animate the character in all eight directions.
For reference:
Forward = F, Backward = B, Left = L, Right = R.
By eight directions i mean, F,B,L,R, FR, FL, BR, BL.
So basically also the diagonals.

Right now i am doing something like this:

    private final ActionListener animListener = (name, isPressed, tpf) -> {
      if(app != null);
        if (name.equals(FORWARD) &isPressed) getPlayer.setAnimation("WalkForward");
        else if(name.equals(BACKWARD)&isPressed) getPlayer.setAnimation("WalkBackward");
        else if(name.equals(LEFT)&isPressed) getPlayer.setAnimation("WalkLeft");
        else if(name.equals(RIGHT)&isPressed) getPLayer.setAnimation("WalkRight");
        else if(name.equals(Right) && name,equals(Forward) && isPressed) getPlayer.setAnimation("WalkForwardRight);
        else getPlayer.setIdleAnimation();

The commented out part is where the problems begin. I thought that i could listen for two Key Inputs simultaneously, but it turns out i cannot. Or i am just doing it wrong. I have read something in the Wiki about ComboMoves but it is not exactly i am looking for.
So basically i need to “listen” if two keys are pressed at the same time, but as far as i know this is not possible the way i do. Does anyone have encountered the same isse? If yes, how did you solve it?

Sure you can.

Read your if/else chain carefully and think about how it would ever go down the if right + forward path. Think hard about what “else” means.

1 Like

Okay, so i tried the following to rule out the part with the if else statements.

    private final ActionListener animListener = (name, isPressed, tpf) -> {
      if(app != null){
          if(name.equals(FORWARD) && name.equals(MOVE_LEFT)) getPlayer().setAnimation("WalkForwardLeft");
          else getPlayer().idelAnimation();

I believe the problem is, that the ActionListener only detects on button pressed. I am not able to access the if part. name.equals(FORWARD) && name.equals(MOVE_LEFT) this is the part where the problem is.

I mean name can not be equal to two different things at the same time. It can be just one of them.

Each button press/release will make a different call I guess. So you can do something like this:

define these booleans somewhere

boolean forward;
boolean left;

then inside the listener do:

if (name.equals(FORWARD)) {
    forward = isPressed;
} else if (name.equals(MOVE_LEFT)) {
    left = isPressed;

if (forward && left) {

Thank you very much, was a little bit confused. This works! :grinning: