Skip to content Skip to sidebar Skip to footer

JavaScript Move Delay And Multiple Keystrokes

Here is my problem: http://testepi.kvalitne.cz/test/ I do not want the delay between a keypress and the movement of the square. I would also like to know how to move diagonally (pr

Solution 1:

First, to avoid the keypress/repeat delay, you have to wrap your program in a loop, and make the state of the keyboard available inside the scope of that loop, secondly to monitor multiple keypresses you need to keep track of individual keydown and keyup events:

var x = 0;
var y = 0;

// store the current pressed keys in an array
var keys = [];

// if the pressed key is 38 (w) then keys[38] will be true
// keys [38] will remain true untill the key is released (below)
// the same is true for any other key, we can now detect multiple
// keypresses
$(document).keydown(function (e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function (e) {
    delete keys[e.keyCode];
});
// we use this function to call our mainLoop function every 200ms
// so we are not relying on the key events to move our square
setInterval( mainLoop , 200 );

function mainLoop() {
     // here we query the array for each keyCode and execute the required actions
     if(keys[37]){
        x -= 10;
        $("#square").css("left", x);
     }

     if(keys[39]){
        x += 10;
        $("#square").css("left", x);
     }

     if(keys[38]){
        y -= 10;
        $("#square").css("top", y);
     }

     if(keys[40]){
        y += 10;
        $("#square").css("top", y);
     }
}

Solution 2:

If you are trying to implement game-like 2d sprite movement, I suggest you have a notion of x and y velocity, rather than moving the sprite a fixed amount on keypress.

So on keypress, add or subtract from x or y velocity.

var xvel = 0,
    yvel = 0,
    x = 0,
    y = 0;

setInterval(function () {
                 y += yvel;
                 x += xvel;
                 $("#square").css("left", x);
                 $("#square").css("top", y);
            }, 16); //run an update every 16 millis

document.addEventListener("keydown", move, false);

function move(event){
  if(event.keyCode==37){
        xvel -= 10;
  }

  if(event.keyCode==39){
        xvel += 10;
  }

  if(event.keyCode==38){
        yvel -= 10;
  }

  if(event.keyCode==40){
        yvel += 10;
  }

}

You would also need to worry about a keyup event, however, as the velocity would stay until you cancelled it out.

You can use setInterval to update the position of the sprite every x milliseconds. (Game tick)

To move diagonally, just add/subtract from the velocity of both x and y simultaneously.

This is just an example, but there are more examples out there on sprite movement.


Solution 3:

have you looked here? you should be able to do diagonal moving by checking if multiple keys have been pressed down without being released.


Post a Comment for "JavaScript Move Delay And Multiple Keystrokes"