Where exactly does the input code go?

Hey guys, so I’m using basic key polling for the most part, and I just pass the key listener as an argument to whatever game state or game object needs it. So something like

Player player = new Player(x, y, keyboard);

And then in player.update() it would be something like


keyboard.update();
if(keyboard.up) player.moveUp();
if(keyboard.down)player.moveDown();
...

So just wondering if this is the right way to do it, because people tell me I should separate input logic from game logic/ update loop, but I’m not really sure where it goes.

Hmmm.

Do you have a class “Keyboard” that is implementing KeyListener?

If so, I’d be strongly tempted to make the class variables ‘up’ and ‘down’ static. Then you don’t have to pass this class to every object that needs to consult keyboard state.

So, in player.update(), yes, reference those variables. As long as you never write to these variables from anywhere except the implementation of KeyPress, KeyRelease, etc., it seems to me they are ok as public variables. Or to be safe, only write a get() and no set() and make the variables private. It might be good to make the variables volatile, but this is where things get a little hazy for me.

This Keyboard class itself wouldn’t have to be called by update(). The ‘up’ and ‘down’ (and ‘left’ and ‘right’ or whatever) variables are updated asynchronously, when the KeyListener implementation methods run (when the keys are pressed).

OK, just thought of an exception. There might be some sort of game state occurrence that triggers where you’d want the keys to do something different. Message that to the Keyboard class via settable variables in the class, and consult them as needed (might be either via a game-loop update cycle or when the KeyPress/Release methods execute).

Think of it this way. You have your game world. It can do amazing things. But, it cannot read your mind. So what, you need is an “interface” between your game world and what you want to do. There is where your input code comes in. You know what else is an interface into your game world? Your actual Graphical User “Interface.”

TL;DR: Wherever you put your GUI code, put your input code.

Make sure you properly synchronize everything. That is, you may want an Action Buffer that runs and flushes every loop cycle. Since you input thread and game thread are different threads, you may want to brush on java concurrency.

Do not be afraid to hard code your mouse input stuff. That stuff usually doesn’t change. Its the keyboard input should be able to work on any key b/c you probably want to support rebinding.

Thanks a lot guys. Sorry for the extremely late reply; been having to prioritize school projects. I’ll take a closer look at the thread when I find the time. Cheers!