简体   繁体   中英

No delay between key press

I am making a game and am having an issue because when the left key is held down the character should go left and when the right key is held down the character should go right. This is all working but the problem is when a key is pressed the character moves slightly in the corresponding direction, waits about half a second until the computer realizes the key is being held down, then the character moves as I want it to. How do I get rid of the delay after the key is held down? Here is my code for moving the character.

 $(document).keydown(function(key) { switch(parseInt(key.which, 10)) { case 37: $('#player').animate({left:'-=5px'}, 1); break; case 39: $('#player').animate({left:'+=5px'}, 1); break; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

If you want key repeat in a controllable fashion, you will have to implement it yourself, as keypress events are fired dependent on the OS's idea of how keys should repeat. That means there may be variable initial and following delays, and holding down two keys at once will cause only one of them to repeat.

I took the code (and that quote) from this answer and mixed it a bit with your code, so it works with your #player element. Please take a look at the question and answer from that link. I removed the original comments to make the code posted in here shorter, but they are useful so you know what you're doing.

The code( jsFiddle ):

function KeyboardController(keys, repeat) {

    var timers= {};

    document.onkeydown= function(event) {
        var key= (event || window.event).keyCode;
        if (!(key in keys))
            return true;
        if (!(key in timers)) {
            timers[key]= null;
            keys[key]();
            if (repeat!==0)
                timers[key]= setInterval(keys[key], repeat);
        }
        return false;
    };

    document.onkeyup= function(event) {
        var key= (event || window.event).keyCode;
        if (key in timers) {
            if (timers[key]!==null)
                clearInterval(timers[key]);
            delete timers[key];
        }
    };

    window.onblur= function() {
        for (key in timers)
            if (timers[key]!==null)
                clearInterval(timers[key]);
        timers= {};
    };

}

KeyboardController({
    37: function() { $('#player').animate({left:'-=5px'}, 100); },
    39: function() { $('#player').animate({left:'+=5px'}, 100); }
}, 100);

I also tweaked your anim settings and the KeyboardController "repeat" parameter to my liking (somewhat randomly to be honest). Play with those parameters and see what you like most.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM