-1

I've been trying to test my keycode skills, and made a new pen with a 'player' moving. but.. I haven't figured out how to make the player move two different directions (for example moving diagonally). Does anyone know what is missing in my current written code? Any help is greatly appreciated.

Here is my code so far:

https: //codepen.io/Skysurfer_kon/pen/BaWNQqb?editors=1010

(The link is dismantled, to go on the link, combine the https: to the rest)

  • Possible duplicate. Go through this once. https://stackoverflow.com/questions/5203407/how-to-detect-if-multiple-keys-are-pressed-at-once-using-javascript – Nisanth Reddy May 13 '21 at 06:23
  • Please consider proving a [MCVE] here , instead of us needing to go offsite to find any code. Don't just mangle the link to get around the requirement to post code with external examples. – Jon P May 13 '21 at 06:34
  • But I don't know how to copy paste my code into stack overflow properly.. – Skysurfer_kon May 13 '21 at 07:21

1 Answers1

0

Even while pressing multiple keys, each keydown and keyup trigger an event.

So what you can do is to have a keys map object which stores what keys are being pressed at the moment when a new keydown event happens.

Have updated your code. It works now.

<body>
    <div><img id = "player" src="https://i.ibb.co/3zzPvKT/Annoying-Dog-sprite.png"></div>
</body>

<script>
var frame = 0;
var y = 6;
var x = 453;
var facingleft = true;
var facingright = false;
  var keys = {};
  
  document.addEventListener("keyup", (e) => {
    keys[e.keyCode] = false;
  });
  
  document.addEventListener("keydown", (e) => {
    keys[e.keyCode] = true;
  
  if (keys[37]) {
    frame++;
    x -= 5;
    player.style.left= (x) + "px";
    if (frame == 1) {
      player.src = 'https://i.ibb.co/0t55kL0/doggo-00.png';
    }
    if (frame == 2) {
      player.src = 'https://i.ibb.co/Y3q13J6/doggo-01.png';
    }
    if (frame == 3) {
      frame = 1;
      player.src = 'https://i.ibb.co/0t55kL0/doggo-00.png';
    }  
  }
  
  if (keys[39]) {
    x += 5;
    frame++;
    player.style.left = (x) + "px";
    if (frame == 1) {
      player.src = 'https://i.ibb.co/NLHJBnJ/doggo-02.png';
    }
    if (frame == 2) {
      player.src = 'https://i.ibb.co/N135wtG/doggo-03.png';
    }
    if (frame == 3) {
      frame = 1;
      player.src = 'https://i.ibb.co/NLHJBnJ/doggo-02.png';
    }
  }
  if (keys[40]) {
    if (y > 200) {
      player.style.top = (y);
    }
    
    if (y < 200) {
    y += 5;
    player.style.top = (y) + "px";
    }
    
  }
  
});

</script>
Nisanth Reddy
  • 5,967
  • 1
  • 11
  • 29