0

I'm practicing moving around objects when a user presses an arrow key. I've got it so when they press right it moved an object to the right and when they press up it moves it up. However, my function is only able to record 1 of these keypresses at once, so they can't move diagonally:

document.onkeydown = function(e){
        if (e.which == 39){    // Move Right
            var position = $("#ball1").position();
            $("#ball1").offset({left:position.left+2});
        }
        if (e.which == 38){    // Move Up
            var position = $("#ball1").position();
            $("#ball1").offset({top:position.top-2});
        }
};

Is there a way to respond to both key presses at the same time?

MarksCode
  • 8,074
  • 15
  • 64
  • 133
  • Check this[LINK] http://stackoverflow.com/questions/4954403/can-jquery-keypress-detect-more-than-one-key-at-the-same-time – shu Feb 04 '16 at 07:05

1 Answers1

0

You have to detect both keydown and keyup

var key = {};
document.onkeydown = function(e){
    if (e.which == 39 || e.which == 38){    // Move Right
        key[e.which] = true;
        if (key[39]) {
            var position = $("#ball1").position();
            $("#ball1").offset({left:position.left+2});
        }
        if (key[38]) {
            var position = $("#ball1").position();
            $("#ball1").offset({top:position.top-2});
        }
    }
};
document.onkeyup = function(e){
    if (key[e.which])
        delete key[e.which];
};
mylee
  • 1,293
  • 1
  • 9
  • 14