0

I've been trying to make a simpler way to check for keypresses for my game. I really thought this would work. I think it's to do with the event listener. Just wondering why its not working. And is there a more efficent way to do this?

Code: `

    const Key = {
      isDown: function(name){ 
        document.addEventListener('keypress', function(event) {
          if(name == event.code){
            return true;
          } else {
            return false;
          };
        });
      }
    };

    function checkKeys(){
      if(Key.isDown('Space')){
        console.log('true')
      };
    };

    function animate() {
      requestAnimationFrame(animate);
      checkKeys();
    };

`

For some reason Key.isDown(KEY) is not returning true, but it is returning false.

olifire
  • 47
  • 6
  • Does this answer your question? [How do I detect keypresses in Javascript?](https://stackoverflow.com/questions/16089421/how-do-i-detect-keypresses-in-javascript) – Skip Nov 08 '22 at 12:17
  • 2
    Also, keypress is deprecated, use keydown or keyup as an event type – Skip Nov 08 '22 at 12:27
  • It's not that I don't know how to detect key presses. I am just trying to develop a cleaner and simpler way of doing it. – olifire Nov 08 '22 at 12:40

0 Answers0