I am creating small game where my object move left and right with arrow keys but that movement is not fast and not even interactive,its like when i press key object move bit later. Any one can suggest how i could make it better in terms of user experience.
here is part of my code that control moving objects(Its two player game so arrow keys for one and A W D for second)
$(document).keydown(function(e){
switch(e.keyCode){
//Move left
case 37:
$('.playerOne').stop().animate({"left":"-=15px"}, '1000', 'linear');
return false;
break;
//Move right
case 39:
$('.playerOne').stop().animate({"left":"+=15px"}, '1000', 'linear');
return false;
break;
//Shoot
case 38:
shotEffect(1,'hitOne','bottom','playerOne');
break;
//Move right
case 68:
$('.playerTwo').stop().animate({"left":"+=15px"}, '1000', 'linear');
return false;
break;
//Move left
case 65:
$('.playerTwo').stop().animate({"left":"-=15px"}, '1000', 'linear');
return false;
break;
//Shoot
case 87:
shotEffect(1,'hitTwo','top','playerTwo');
break;
}
});
Thanks in advance
One reason for slow response to keyboard input is that you're listening for the JavaScript keydown event or similar keyboard events. However, repeated keyboard events are subject to the keyboard initial repeat delay and repeat rate as set in the user's control panel.
For example, on a Windows system with default settings, the initial keyboard delay is set rather long—in the neighborhood of half a second. So you get one initial keydown immediately when the key is pressed, but the first repeated keydown doesn't happen for another half-second. And after that initial delay, the frequency of keydown events is subject to the user's repeat rate.
What you need to do instead is keep track of which keys are down at any time, and then in your game loop—presumably using requestAnimationFrame() or setInterval()—check which keys are currently down. This way the keyboard repeat timing is not controlled by the user's settings but by the speed of your game loop.
One easy way to do this is with the keydrown library. Try the demo on that page and see if it does what you need.
Also, here is a StackOverflow answer with a discussion of the issue and some similar code.
Between the two I'd recommend keydrown because it's more fully developed, but it's worth looking at the SO answer too.
There could be other issues in your code too, of course, but this is one to definitely fix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With