Listen to multiple keydowns

后端 未结 3 460
暗喜
暗喜 2020-12-03 12:42

I\'m trying to let a user move an element on the page using the arrow keys. So far, I have movement working for up/down/left/right, but not for diagonal (two arrow keys pres

3条回答
  •  攒了一身酷
    2020-12-03 13:08

    Logically this sounds rather simple:

    1. the first key triggers a key down event, store this event in a stack
    2. then the second key triggers a key down event, store this event in a stack
    3. now you have two key downs and no key up
    4. if a key up fires you have three possibilities
      1. you have only one event => go in that direction
      2. you have two events => go diagonally
      3. you have more than two events, or an invalid option (e.g. right and left) => do nothing, or whatever you feel like
    5. clear the stack

提交回复
热议问题