Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth keyboard input in javascript

Tags:

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?

like image 759
user11914177 Avatar asked Nov 21 '25 15:11

user11914177


1 Answers

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.
like image 122
Robo Robok Avatar answered Nov 24 '25 03:11

Robo Robok