一次按下javascript多个键会出错

时间:2013-03-18 11:20:03

标签: javascript events keydown

 $(document).keydown(function(e){
    var key=e.which;
    //to prevent reversing, add the possible value of d which hinders the snake to go to desired direction
    if(key=="37"&&d!="right"){
        if(p==true){
            clearInterval(game_loop);
            game_loop=setInterval(paint,60);
            p=false;
            d="left";
        }
        else{
            d="left";
        }
    }
    else if(key=="38"&&d!="down"){
        if(p==true){
            clearInterval(game_loop);
            game_loop=setInterval(paint,60);
            p=false;
            d="up";
        }
        else{
            d="up";
        }
    }
    else if(key=="39"&&d!="left"){
        if(p==true){
            clearInterval(game_loop);
            game_loop=setInterval(paint,60);
            p=false;
            d="right";
        }
        else{
            d="right";
        }
    }
    else if(key=="40"&&d!="up"){
        if(p==true){
            clearInterval(game_loop);
            game_loop=setInterval(paint,60);
            p=false;
            d="down";
        }
        else{
            d="down";
        }
    }
    else if(key=="32"){
        if(p==false){
            clearInterval(game_loop);
            p=true;
        }
        else{
            game_loop=setInterval(paint,60);
            p=false;
        }
    }
})

这段代码定义了我的蛇的keydown。问题是。每当我同时按下2个键或者如果我按下并快速离开(也许其他组合也可能)游戏结束。我快速按下2个键后,检查碰撞到自己身体的功能返回true喜欢向下和向左..

怎么可以修理?

1 个答案:

答案 0 :(得分:1)

你试过e.preventDefault()..

$(document).keydown(function(e){
    var key=e.which;
    e.preventDefault();