AlexMorley-Finch
AlexMorley-Finch

Reputation: 6955

Keydown pauses after first keyress, and subsequent keypresses

Go Here

Use UP and DOWN keys

When I press a key, the red box moves down, pauses, then moves the rest.

How do I remove the pause?

Upvotes: 6

Views: 1712

Answers (3)

Hans Z
Hans Z

Reputation: 4744

You should use a setInterval update function to update your location. Your keyup and keydown functions will set flags that either move your paddle up or down. Demo: http://jsfiddle.net/DH5qT/

    var movedir = 0; // up if 1, down if -1, none if = 0.
    var interval = setInterval(function(){
        paddle_y = paddle_y + (5 * movedir);
        draw_paddle();
    } , 1);

    function move_down(){
        movedir = -1;
        draw_paddle();
    }
    function move_up(){
        movedir = 1;
        draw_paddle();
    }

Upvotes: 1

MaxArt
MaxArt

Reputation: 22617

You can't, since it depends on the OS keyboard settings to prevent multiple letter typing on a slighly long pressure of the key.

P.S.: don't register one event for each key you want to monitor. Do this instead:

$(document).keydown(function(e){
    if (e.keyCode == 38) { 
        move_down();
        return true;
    } else if (e.keyCode == 40) { 
        move_up();
        return true;
    }
});​

And return true; doesn't actually do anything meaningful...

What you actually should do is to use the keydown and keyup events to do what they're supposed to do in a game (I think it is), i.e., start and stop the movement.

Upvotes: 2

Marcel Korpel
Marcel Korpel

Reputation: 21763

You should follow keydown as well as keyup and use an interval to move the paddle more smoothly.

Demo: http://jsfiddle.net/M7TKc/16/

var paddle = $("#paddle");
paddle.css({backgroundColor: "red", height:"100px", width:"25px", position: "absolute"});

var paddle_y = 0,
    moving = 0;  /* added */

draw_paddle();

window.setInterval(function () {  /* added */
    if (moving != 0) {
        paddle_y += moving;
        draw_paddle();
    }}, 100);

function move_down(){
    moving = -10;
}
function move_up(){
    moving = 10;
}

function draw_paddle(){
    paddle.css({top: paddle_y+"px"});
}

$(document).keypress(function(e) {
    if(e.which == 13) {
        // stop on "ENTER"
        moving = 0;
    }
});
$(document).keydown(function(e){  /* changed */
    if (e.keyCode == 38)
        move_down();
    else if (e.keyCode == 40)
        move_up();

});

$(document).keyup(function(e){  /* added */
    if (e.keyCode == 38 || e.keyCode == 40)
        moving = 0;
});

Upvotes: 6

Related Questions