Keylistener in Javascript

后端 未结 5 811
走了就别回头了
走了就别回头了 2020-12-02 23:22

I\'m looking for a KeyListener for a game I\'m developing in JavaScript. I have no idea how this would work in real code but it would be something like this:

5条回答
  •  自闭症患者
    2020-12-02 23:33

    A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):

    window.onkeyup = function(event) {
        let key = event.key.toUpperCase();
        if ( key == 'W' ) {
            // 'W' key is pressed
        } else if ( key == 'D' ) {
            // 'D' key is pressed
        }
    }
    

    Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))

提交回复
热议问题