0
\$\begingroup\$

I need a higher level abstraction for keyboard input for a 2.5D platformer. Like I know left and right is pressed, but I want to consider things like, left is held down for more than one second, start running, right is pressed while left is just released so slow down and turn, things like that.

What are some considerations on this regard?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The way I process keys presses in my applications is I have 2 lists ranging from 0-127 (all ASCII keys). One is for a key_duration_state and the other for a key_hold_state. I don't know what sort of event listener you're using, but take a generic onKeyDown/Up(int key) listener function for example. This functions job is to let you know when a key has been pressed, where key was the value of the key pressed. I have it return 1 as long as the key is still pressed, and 0 when it's released. All I need in order to register every ASCII keys press/release state is pass my list to the function. Same goes for duration. Just increment that keys duration_state as long as its pressed. Then reset it to zero upon release:

// tells if its pressed
bool onKeyDown(int key) {
    key_hold_state[key] = 1;
    key_duration_state[key]++;
}

// tells if its released
bool onKeyUp(int key) {
    key_hold_state[key] = 0;
    key_duration_state[key] = 0;
}

What I do to determine if a key is being held for a duration is use my list key_hold_state which stores whether the key is pressed down or not. Then I have another function, say isHeldFor(int duration) which checks if that key was held for the duration:

bool wasHeldFor1s = keyListener.isHeldFor('A', DURATION_1s);
bool isHeldFor(int key, int duration) {
    return duration_held_state[key] >= duration);
}

This is just my approach. There could be a better way, but storing every keys states into lists is a good move. Keeps it clear, concise, and organized.

\$\endgroup\$
3
  • \$\begingroup\$ I also have this information, but my question is how do I go further with this information to answer more higher level questions for a 2.5 d platformer. \$\endgroup\$
    – eguneys
    Sep 2, 2022 at 8:21
  • \$\begingroup\$ I don't understand what you mean, you'll have to elaborate on what you're trying to do more specifically. Are you asking about keyboard input or game mechanics? \$\endgroup\$ Sep 3, 2022 at 20:36
  • \$\begingroup\$ Answer what to do on situations like: up press, release, up press 2 sec release, up press 1 seconds right pressed up released. up pressed, down pressed up released. All kinds of combinations create different situations of possibilities. How to handle these in a 2.5 d platformer. \$\endgroup\$
    – eguneys
    Sep 3, 2022 at 22:47

You must log in to answer this question.

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