使用jQuery模拟4路运动

时间:2015-03-25 15:32:43

标签: javascript jquery html

我正在JQUERY制作一个简单的游戏,我想知道如何使用JQUERY进行简单的4向运动(向上,向下,向左,向右)我有:

HTML

<div id="dot"></dot> <!-- the character -->

jquery的

$(document).keydown(function(e) {
        if(e.which == 37) {

        } else if (e.which == 38){

        } else if (e.which == 39){

        } else if (e.which == 40){

        }
    });

编辑:该动作是模拟“世界上最难的游戏”,你可以在这里找到:http://www.el-juego-mas-dificil-del-mundo.com/。我需要它软(我不知道如何解释它xD)

1 个答案:

答案 0 :(得分:0)

首先,将</dot>更改为</div>

这不是perfect答案,但对您来说这是一个好的开始。 (还有其他更好的优化方法,我确定,但我不具备相应的技能)。

然后,您可以使用.animate()移动您的点:

$(document).keydown(function (e) {
    if (e.which == 37) {
        $("#dot").animate({
            left: "-=5"
        }, 5);
    } else if (e.which == 38) {
        $("#dot").animate({
            top: "-=5"
        }, 5);
    } else if (e.which == 39) {
        $("#dot").animate({
            left: "+=5"
        }, 5);
    } else if (e.which == 40) {
        $("#dot").animate({
            top: "+=5"
        }, 5);
    }
});

并将div position设为absolute

.dot {
    position: absolute;
    top:0;
    left:0;
}

JsFiddle:http://jsfiddle.net/ghorg12110/6c5kpj69/