Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS holding down a key has a delay

I am learning JavaScript and I am trying to program a small game. I want that something in my game moves consistently while I hold down a key. This is what I came up with so far:

document.onkeydown = onKeyDownListener;

function onKeyDownListener(evt) {
    var keyCode = evt.which || evt.keyCode;
    if(keyCode == 37) {
        move();
    }
}

My problem is that when I press down the key move gets called once, then there is a pause and after that pause move gets called repeatedly as I intend. It goes like this: m......mmmmmmmmm when 'm' stands for move and'.' is the pause. Is there a way to get rid of the pause?

Here is a GIF of what happens:

GIF of my problem

like image 938
Yannic Avatar asked Mar 20 '18 21:03

Yannic


1 Answers

I'm pretty sure you have this problem because you're not depending on a game loop to run your game. If you were, you wouldn't be running into this problem because the game loop at each interval would check if the key is pressed. Your web app is only reacting to each key press as they happen.

I highly recommend you read this tutorial:

W3 HTML Game - Game Controllers

https://www.w3schools.com/graphics/game_movement.asp

Read the "Keyboard as Controller" section. The "setInterval" method induces the game loop in this example.

I used it as a reference to write game code for myself.

This is code from the W3 tutorial. It also goes on to teach collision detection as well.

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            myGameArea.keys = (myGameArea.keys || []);
            myGameArea.keys[e.keyCode] = true;
        })
        window.addEventListener('keyup', function (e) {
            myGameArea.keys[e.keyCode] = false; 
        })
    }, 
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

 function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0; 
    if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -1; }
    if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; }
    if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
    if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
    myGamePiece.newPos(); 
    myGamePiece.update();
}
like image 86
lewdev Avatar answered Sep 22 '22 10:09

lewdev