1

I'm making a simple game in JQUERY and I want to know how to make a simple 4 way movement (up, down, left, right) with JQUERY I have this:

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){

        }
    });

EDIT: The movement is to simulate the "Worlds hardest game" which you can find here: http://www.el-juego-mas-dificil-del-mundo.com/. I need it to be soft (I don't know how to explain it xD)

hooliii
  • 11
  • 2

1 Answers1

0

First thing is to change your </dot> into </div>.

This is not the perfect answer, but it can be a good start for you. (There is other better optimized ways to do it I'm sure, but I don't have the skills for that).

Then, you can use .animate() to move your dot :

$(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);
    }
});

And set your div position as absolute:

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

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

Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35