3

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?

3
  • stackoverflow.com/questions/5203407/… Commented May 21, 2020 at 18:08
  • @MoloF I don't get how this program should work, I started programming in js 3 days ago, also this is deprecated Commented May 21, 2020 at 18:40
  • @MoloF so I got how that is working Commented May 21, 2020 at 20:09

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

You're welcome! I hope you'll be comfortable with requestAnimationFrame().
It's absolutely no problem, because I use requestAnimationFrame() anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.