Skip to main content
1 of 3

Good design for player input handling in 2d game

I am working on a java 2d game. Keeping things short, I'd like to improve my current input handling. Basically the player can move up/down/left/right with WASD, perform an attack with mouse left click and shoot with mouse right click.

Following this article I implemented my own finite state machine like:

interface State {
 State transition(Input input, double deltatime)

 void update(Input input, Entity e, double deltatime)
}

where Entity is player (I'm using some variant of entity-component-system, but its not relevant here). Then a state would look like this:

class WalkState implements State {
   State transition(Input input, double deltatime) {
     if (input.isShooting()) 
         return new ShootState()
     if (input.isAttacking())
         return new AttackState()
     if (!input.isMoving())
         return new IdleState()
     return null;
   }

   void update(Input input, Entity e, double deltatime) {
     if (input.isUp()) 
        //move up
     if (input.isDown())
        //move down
     ...
   }
}

The code that updates the player every tick looks like this:

if player is blocked executing animation
    return; // do not react to new input
var currState = player.getState()
newState = currState.transition(input, deltatime);
if (newState != null) 
    player.setState(newState)
player.getState.update(input, player, deltatime)
// update animation by getting a string description from the state

My doubts are that maybe using a finite state machine for this is not optimal and that the input taking class reimains made of boolean fields to be checked. I know of command pattern but I thought states gave me more flexibility. For instance I could insert timers into some state to trigger extra actions. Any suggestion is appreciated