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 keyup
events, if the keyCode returned byevent.which
is>=37 && <=40
means arrow keys were used. Store inside aK
(keys) Object a boolean value for key-number property.Interval:
Inside a
window.requestAnimationFrame
increase or decrease thex
,y
position of your element if a key-number property (inside ourK
object) 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..)about that interval,
http://jsfiddle.net/fbFuW/21/
I messed around with a similar thing and here's a solution I came across that works.
Demo
The problem with the delay seems to be that most browsers will take the first input (on keyDown) and then they have half a second delay before running the functions over and over. If we don't recall the function on keydown, but rather have an interval checking an associative array where we store what keys are being held down, that seems to smooth out movement. It also allows for multiple keys to be pressed at once, which means diagonal movement. Then we'll remove the respective keys by using the keyup event.
In this solution you have two ways of managing the speed of the element you're moving.
I find that 20 ms on the interval frequency gives you fairly smooth movement.
I realize that this is a really old thread, but I figured I'd contribute anyway.
How about this using jquery animate. It almost prevent delayed movement.
See demo