2

I am currently doing this for input handling:

var upKey = false;
var downKey = false;
var leftKey = false;
var rightKey = false;

var sqrt2over2 = 0.707106781;
var MoveSpeed = 20.0;
var Horizontal = false;
var Vertical = false;

document.onkeyup=function(e){
    if(e.which == 87)
    {
        Vertical = false;
        upKey = false;
    }
    if(e.which == 83)
    {
        Vertical = false;
        downKey = false;
    }
    if(e.which == 65)
    {
        Horizontal = false;
        leftKey = false;
    }
    if(e.which == 68)
    {
        Horizontal = false;
        rightKey = false;
    }
}

document.onkeydown=function(e){
    //Up arrow key
    if(e.which == 87) upKey = true;
    //Down arrow key
    if(e.which == 83) downKey = true;
    //Left arrow key
    if(e.which == 65) leftKey = true;
    //Right arrow key
    if(e.which == 68) rightKey = true;

    var diagonals = Vertical && Horizontal;
    if(downKey)
    { 
        Vertical = true;
        moveY -= diagonals ? MoveSpeed * sqrt2over2: MoveSpeed;
    }
    if(upKey)
    {
        Vertical = true;
        moveY += diagonals ? MoveSpeed * sqrt2over2: MoveSpeed;
    }
    if(rightKey)
    {
        Horizontal = true;
        moveX -= diagonals ? MoveSpeed * sqrt2over2: MoveSpeed;
    }
    if(leftKey)
    {
        Horizontal = true;
        moveX += diagonals ? MoveSpeed * sqrt2over2: MoveSpeed;
    }   
}

I need to have this work so that the screen doesn't pause at all when you press another direction or multiple directions. Currently there is a bit of a pause. Is there a setting to turn off this pause or is there another approach to pooling and responding to input which circumvents this dilemma?

Pro-grammar
  • 365
  • 2
  • 17

2 Answers2

2

I think the pause is due to key repeat rate. Take a look at this question / answers: remove key press delay in javascript

Community
  • 1
  • 1
sinelaw
  • 16,205
  • 3
  • 49
  • 80
1

The problem is that you're using the operating system's key repeat as the 'tick' for moving. Instead of this you should use setInterval to create your own tick for moving, and then monitor keydown / keyup to change the direction of movement.

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99