keydown event doesn't work

1.1k Views Asked by At

i want make player controller for my 1st game in jquery but something is wrong. Can you help me, please?

$('canvas').keydown(function(e) {
    alert('in function');
    if (e.keyCode == 37) {//37 - strzalka w lewo
        moveleft();
    }
    if (e.keyCode == 39) {//39 - strzalka w prawo
        moveright();
    }
    if (e.keyCode == 40) {//40 - strzalka w dol
        movedown();
    }
    if (e.keyCode == 38) {//38 - strzalka w gore
         moveup();
    }
    if (e.keyCode == 32) {//32 - spacja

    }
});

function moveup() {
    gracz.speedY -= 1; 
}

function movedown() {
    gracz.speedY += 1; 
}

function moveleft() {
    gracz.speedX -= 1;
}

function moveright() {
    gracz.speedX += 1;
}

when i press arrows, event handler doesn't work

1

There are 1 best solutions below

0
On BEST ANSWER

Retrieving key-related events on a canvas is unreliable at best. Use a parent element of the canvas instead, or even the window, for example:

$(window).keydown(function(e) {
    // your code here...
});

Working example

Also note that you can simplify your code by putting the functions to be run under the keypress events within an object, keyed by their keycode values, like this:

var gracz = {
    speedY: 0,
    speedX: 0,
    keydown: {
        '37': function() { gracz.speedX -= 1; }, // left
        '38': function() { gracz.speedY -= 1; }, // up
        '39': function() { gracz.speedX += 1; }, // right
        '40': function() { gracz.speedY += 1; }, // down
        '32': function() { console.log('SPACE'); } // space
    }
};

$(window).keydown(function(e) {
    gracz.keydown[e.which](); 
    console.log(gracz);
});

Working example