Diagonal move not working and issue on left-longPress/right simultaneous
But on double keypress the ship goes crazy!
$(document).bind('keydown', function(e) {
var box = $("#plane"),
left = 37,
up = 38,
right = 39,
down = 40
if (e.keyCode == left) {
box.animate({left: "-=5000"},3000);
}
if (e.keyCode == up) {
box.animate({top: "-=5000"},3000);
}
if (e.keyCode == right) {
box.animate({left:"+=5000"},3000);
}
if (e.keyCode == down) {
box.animate({top: "+=5000"},3000);
}
});
$(document).bind('keyup', function() {
$('#plane').stop();
});
Relying on keyboard events to move an element will make it dependent on the OS key-interval delay. Instead, use the game interval and check the pressed keys stored inside an Object
On
keydown keyupevents, if the keyCode returned byevent.whichis>=37 && <=40means arrow keys were used. Store inside aK(keys) Object a boolean value for key-number property.Interval:
Inside a
window.requestAnimationFrameincrease or decrease thex,yposition of your element if a key-number property (inside ourKobject) istrue(if(K[37])).Diagonal movement:
Moving an element diagonally using simultaneously i.e. the ↑ and → needs a compensation for the diagonal distance:
1 / Math.sqrt(2)(0.7071..)or here’s a slight remake using
new Set()to keep record of the currently pressed keyboard keys, andnew Map()to register functions for every pressed key: