2
\$\begingroup\$

currently i'm developing a 2D game in my spare time and i'm confused on how to handle the input from the player.

Currently my game uses the state design pattern, each game state is a different object such as Inventory, Playing, Paused etc. All of these states implement an interface called State that have a Render and Input method that is called on whatever the "Current state" is in the game engine.

So my question is would you use multiple key listeners or key bindings, one for each state since the input the player will do differs dramatically between the different game states or would you use one key listener or keybinding somehow? Is there a best practice for this?

Thanks.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Both approaches will work. Using the "one per state" will help a bit more keep stuff more localized. \$\endgroup\$
    – Vaillancourt
    Mar 24, 2018 at 1:35
  • \$\begingroup\$ As a side note, you may want to structure input handlers as a Chain of Responsibility so that the game may be paused while the inventory is open. \$\endgroup\$ Apr 2, 2021 at 5:12

1 Answer 1

0
\$\begingroup\$

Maybe use flags?? (I use same thing in C#)

   On_Keypress(key){
    if(key==Q){
        if(inventoryopen){

        dropitem(selected)

        }else if(is_dying){

        slow_bloodlose();

        }
      }
    }

On your inventory open method :

On_Inv_open(){
inventoryopen=true;
}

On your inventory close method :

On_Inv_close(){
inventoryopen=false;
}

Or set a int sate

if(sate==1)//Inventory state
if(state==2)//Shop state
//
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .