user11914177
user11914177

Reputation: 955

Smooth keyboard input in javascript

I have started to program in Javascript to make a 3D application with WebGL. I need to receive the keyboard inputs in an other way, because the way I do it, like this:

var keys = {};
window.addEventListener("keydown", (e) =>  {
    keys[e.which] = true;

    updateKeys();
});

window.addEventListener("keyup", (e) =>  {
    delete keys[e.which];

    updateKeys();
});



function updateKeys() {
    for(var i in keys) {
        if(keys[87] === true) {
            //Move
        }
    }
}

produces a very rough result and there is stuttering. Is there some way I can get a smooth input?

Upvotes: 3

Views: 1157

Answers (1)

Robo Robok
Robo Robok

Reputation: 22683

It's stuttering, because you run your movement along with the key events. And your key events take advantage of event.repeat, which happens when you keep your key pressed.

You should do two things:

  1. In your keydown listener, add the following line to ignore repeated presses:
if (e.repeat) return;
  1. Move your movement logic somewhere else, namely window.requestAnimationFrame() handler.

Upvotes: 2

Related Questions