How to create a motion script for a div?

Asked

Viewed 196 times

1

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Character Movement Script</title>
    <style>

        body {
            background-color: rgb(166, 166, 172);
        }

        div#player {
            width: 60px;
            height: 60px;
            background-color: rgba(255, 0, 0, 0.673);
            border: 2px solid rgb(0, 0, 0);
            position: relative;
            top: 0;
            left: 0;
        }
    
    </style>
</head>
<body>

<div id="player"></div>

<script>

var player = window.document.querySelector("#player");

window.addEventListener("keydown", function() {
  player.style.left = "10px";
});

</script>

</body>
</html>

I wonder how I could do when I press the right arrow button to div#player start going right when I hit the left button it goes left and the same thing will happen to the up and down arrow. The problem is that I’m not able to solve this, because what happens is that when I press any key to div#player going 10px to the right and when I press again it won’t go any more and I don’t want it, it’ll just go to a determida direction just with the arrow keys an example is in a video I saw on Youtube, only changes that I wanted in this case up, straight, down and left as I would do it?

  • @Sam was not what I wanted! the question is different from the question you duplicate.

  • And the question you duplicated the guy is using Jquery and I want pure JS, has nothing to do.

  • 1

    player.style.left = "10px", here you are defining that the position will be 10px from the left. For the movement you should not use an absolute value, but go incrementing.

  • @Anderson Carlos Woss as so I did not understand?

  • 1

    Playing with the idea... https://jsfiddle.net/acwoss/akg426L8/

  • consider using the element canvas

  • @Vik necessarily it does not need to use the canvas for that reason.

Show 2 more comments

2 answers

2

Take the keyCode at the event keydown, that are 37 to 40 of the arrows. Then just take the current position of the div and increment or decrease 10px left if the keyed arrow is left or right, and top if the keyed arrow is up or down.

Example (see explanatory comments):

var player = window.document.querySelector("#player");

window.addEventListener("keydown", function(e) {
   var tecla = e.keyCode; // código da tecla
   
   // o sinal de "+" é para converter o valor em número
   var pos_x = +player.style.left.replace("px", ""); // retiro o px da posição
   var pos_y = +player.style.top.replace("px", ""); // retiro o px da posição
   var move = 10; // o quanto em pixels vc quer mover

   if(tecla == 37){ // seta ←
      player.style.left = pos_x-move+"px";
   }else if(tecla == 38){ // seta ↑
      player.style.top = pos_y-move+"px";
   }else if(tecla == 39){ // seta →
      player.style.left = pos_x+move+"px";
   }else if(tecla == 40){ // seta ↓
      player.style.top = pos_y+move+"px";
   }
});
body {
   background-color: rgb(166, 166, 172);
}

div#player {
   width: 60px;
   height: 60px;
   background-color: rgba(255, 0, 0, 0.673);
   border: 2px solid rgb(0, 0, 0);
   position: relative;
   top: 0;
   left: 0;
}
<div id="player"></div>

2


Dude, it’s pretty simple, but for you it might be a little more complex to do, but I’ll comment on every part of the code since you’re having a hard time implementing this in your project.

  1. Well, first of all inside the tag script initialize three variables that we will use in the future in the script.

    var horizontalAxisX = 0;
    var verticalAxisY = 0;
    var pixels = "px";
    
  2. Then add the event keydown in the window and call the function playerMovement, you did basically the same thing, only changes that you called an anonymous function.

    window.addEventListener("keydown", playerMovement);
    
  3. Now within the function playerMovement create a variable player with reference to the div="player" there in HTML.

    var player = window.document.getElementById("player");
    
  4. And we also need to have a variable that saves the value of the key pressed so that in the future we can use this value. Then create a variable key and store the value event.keyCode which is the value of the keystroke stored in the variable key.

    var key = event.keyCode;
    
  5. Now comes the easiest part which is to use a condition structure that would be the if, we will compare the value of the variable key with the value of the key we want. It is worth mentioning one thing each keyboard key has a code(number) this code is what we will use to make the comparison. In case you do not know the code of the key you want, you can access a site that generates the code of the pressed key, for example the site keycode on the site just press the key and automatically it will return the code of the key you pressed.

    if (key == 37) {
        // tecla da esquerda
        // Se o código da tecla pressionada for igual a 37 execute isso.
    }
    
  6. The number 37 would be the code of the left key, we also need to compare the code of the pressed key with the other keys we want, that would be up, right, down. Let’s use a else if for that reason.

    else if (key == 38) {
        // tecla de cima
        // Se o código da tecla pressionada for igual a 37 execute isso.
    }
    
    else if (key == 39) {
        // tecla da direita
        // Se o código da tecla pressionada for igual a 37 execute isso.
    }
    
    else if (key == 40) {
        // tecla de baixo
        // Se o código da tecla pressionada for igual a 37 execute isso.
    }
    
  7. We need to make sure that every time the left key is pressed it is increased by another 10, that 10 has to be negative, why negative? ahead will become clearer for you. Inside the first if put the following code.

    horizontalAxisX += -10;
    
  8. Now we need to get div="player" go left, then we would have to use the property left CSS. Only that the value will not be a static pixel will be a dynamic pixel in case we get the code horizontalAxisX += -10; and concatenate with the variable pixels that has the value as a String that is px, thus the left will be -10px.

    player.style.left = horizontalAxisX + pixels;
    
  9. That same concept from above, we will inplementate to the other keys we will only change some things what will change, will be to the top key instead of being horizontalAxisX place verticalAxisY on the top and bottom line and instead of being left place top and in the right key you will only change the variable horizontalAxisX += 10; to increase a positive value 10 and at the bottom key you will put verticalAxisY on the top and bottom row and place it to increment a positive value.

    else if (key == 38) {
         verticalAxisY += -10;
         player.style.top = verticalAxisY + pixels;
    }
    
    else if (key == 39) {
         horizontalAxisX += 10;
         player.style.left = horizontalAxisX + pixels;
    }
    
    else if (key == 40) {
         verticalAxisY += 10;
         player.style.top = verticalAxisY + pixels;
    }
    

Then the code would be completely like this.

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Character Movement Script</title>
    <style>

        body {
            background-color: rgb(166, 166, 172);
        }

        div#player {
            width: 60px;
            height: 60px;
            background-color: rgba(255, 0, 0, 0.673);
            border: 2px solid rgb(0, 0, 0);
            position: relative;
            top: 0;
            left: 0;
        }
    
    </style>
</head>
<body>

<div id="player"></div>

<script>

var horizontalAxisX = 0;
var verticalAxisY = 0;
var pixels = "px";

window.addEventListener("keydown", playerMovement);

function playerMovement() {
    var player = window.document.getElementById("player");
    var key = event.keyCode;
    
    if (key == 37) {
        // tecla da esquerda
        // Se o código da tecla pressionada for igual a 37 execute isso.
        horizontalAxisX += -10;
        player.style.left = horizontalAxisX + pixels;
    }

    else if (key == 38) {
        // tecla de cima
        // Se o código da tecla pressionada for igual a 37 execute isso.
        verticalAxisY += -10;
        player.style.top = verticalAxisY + pixels;
    }

    else if (key == 39) {
        // tecla da direita
        // Se o código da tecla pressionada for igual a 37 execute isso.
        horizontalAxisX += 10;
        player.style.left = horizontalAxisX + pixels;
    }

    else if (key == 40) {
        // tecla de baixo
        // Se o código da tecla pressionada for igual a 37 execute isso.
        verticalAxisY += 10;
        player.style.top = verticalAxisY + pixels;
    }
}

</script>

</body>
</html>

Just to give an extra in the code, if you wanted to add a key to reset the positions of the div="player" and variables using the space key or any other key, you could do so.

else if (key == 32) {
    player.style.top = "0";
    player.style.left = "0";
    horizontalAxisX = 0;
    verticalAxisY = 0;
}

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Character Movement Script</title>
    <style>

        body {
            background-color: rgb(166, 166, 172);
        }

        div#player {
            width: 60px;
            height: 60px;
            background-color: rgba(255, 0, 0, 0.673);
            border: 2px solid rgb(0, 0, 0);
            position: relative;
            top: 0;
            left: 0;
        }
    
    </style>
</head>
<body>

<div id="player"></div>

<script>

var horizontalAxisX = 0;
var verticalAxisY = 0;
var pixels = "px";

window.addEventListener("keydown", playerMovement);

function playerMovement() {
    var player = window.document.getElementById("player");
    var key = event.keyCode;
    
    if (key == 37) {
        horizontalAxisX += -10;
        player.style.left = horizontalAxisX + pixels;
    }

    else if (key == 38) {
        verticalAxisY += -10;
        player.style.top = verticalAxisY + pixels;
    }

    else if (key == 39) {
        horizontalAxisX += 10;
        player.style.left = horizontalAxisX + pixels;
    }

    else if (key == 40) {
        verticalAxisY += 10;
        player.style.top = verticalAxisY + pixels;
    }

    else if (key == 32) {
        player.style.top = "0";
        player.style.left = "0";
        horizontalAxisX = 0;
        verticalAxisY = 0;
    }
}

</script>

</body>
</html>

And if you want to increase the speed of div#player just increase the value of the variables increment horizontalAxisX and verticalAxisY and if you want to slow down, just slow down.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.