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
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:
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:
Working example