0

I am building a 2D platformer game. And I didn't yet write the script for jumping and all that, but I have basic script to move in all directions:

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
      if (yVel <= 4){
        yVel += speed;
      }else{
        yVel = yVel
      }
      y -= yVel;

    }
    else if (e.keyCode == '40') {
      if (yVel <= 4){
        yVel += speed;
      }else{
        yVel = yVel
      }
      y += yVel;
    }
    else if (e.keyCode == '37') {
      if (xVel <= 4){
        xVel += speed;
      }else{
        xVel = xVel
      }
      x -= xVel;
    }
    else if (e.keyCode == '39') {
      if (xVel <= 4){
        xVel += speed;
      }else{
        xVel = xVel
      }
      x += xVel;
    }

The result was supposed to be script which would let you move diagonally if you need to, but what I've got is when you press up key, for example, it goes up, but when you press any other button, for example, right, then it stops the up movement and only goes right. There is the project code: https://repl.it/@MarkelL/Break-It This is the project itself: https://break-it--markell.repl.co/

Explanations would be really appreciated. Thank you!

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
MarkelL
  • 9
  • 2

1 Answers1

0

That's because onKeyDown is being overwritten by the second keypress. You'll want to write an event listener for up/down keys and left/right keys (that way they can overwrite one another) you're listening for - if you're using a f2d framework like Phaser, they have specified keyDown events you can bind to. Here is a way to detect multiple key presses

  • I still don't really understand how to do it. I know I am dumb. And I am using plain html editor (Repl.it) – MarkelL Jan 05 '19 at 02:12
  • And to make it even worse, it didn't work with arrays very much, so I do not understand how they work :( – MarkelL Jan 05 '19 at 02:17