Search code examples
javascripteventsbrowserkeydowncreatejs

Javascript - getting keydown in a loop


I am trying to make a browser game (using createjs, if this makes a difference) and the problem I'm trying to figure out is how do I get the event keydown in a loop, and no sudden.

For example,

createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", function() {

    // here
    if (isUpArrowKeyPressed) {
        movePlayerUp(); // This is an example, ignore this
    }

});

So this way, if the key is pressed for exactly 1 second it would do what is inside it 60 times. (60fps)

Any way to do this?


Solution

  • You'll want to pass in the event parameter to your function. From there you'll be able to see which key was pressed

    createjs.Ticker.addEventListener("keydown", function(e) {
       var keyCode = e.keyCode
    
       // Compare the keycode
       if (keyCode === 57) {
           movePlayerUp(); // This is an example, ignore this
       }
    
    });