I'm looking for a way to retrieve the last key pressed even when other keys might be pressed for a top-down four-directional game. For example:
- W is pressed → Move up
- D is pressed → Move right
- S is pressed → Move down
The above I can get to work fine using a stack. When S is released, then we start moving right again, and when D is released, we go back to moving up. The issue arises when trying to release (say W) and then pressing W again to move up before S and D are released.
I've tried using arrays and lists to solve this problem (to use flags or remove a key from any point in the collection), but it results in whatever key is last in the if statements to check for the movement keys being given the priority.
Any help is greatly appreciated. If there's anything else I could provide please let me know.
Edit - a more detailed example:
- Player is currently standing still.
- User presses W to move the player up. This key is stored as the current movement key on a stack and as long as the key is pressed (checking per frame), the player will continue to move up.
User presses D to move the player right. The D key is stored as the current movement key on the same stack W was stored on. W is not the current movement key anymore.
User releases the W key - since this is stored on a stack, we know W was released but we cannot remove it from the stack (but we do know it is on the stack). I do not want to just keep adding the keys to the stack, thus the reason we check if the stack contains the key.
- User presses the W key again. Since D is still the current movement key, and since we weren't able to remove W from the stack, we cannot add it to the stack again.