Search code examples
javascriptp5.js

Up and down Movement in p5.js (and using WASD)


How can I use the keyboard to make a character move in p5? I mean, more then left and right... I would also like to use the WASD keys. I've used this (shape as a placeholder):

https://editor.p5js.org/TheDiamondfinderYT/present/8ZqV2LsVB

function keyPressed() {
  if (keyCode === LEFT_ARROW||keyCode === 65) {
    left()
  } else if (keyCode === RIGHT_ARROW||keyCode === 68) {
    right();
    
    if (keyCode === UP_ARROW) {
    up()
  } else if (keyCode === DOWN_ARROW) {
    down()
  }
}

Could anyone point me in the right direction?


Solution

  • You just made a few mistakes. For example, in this code:

    else if (keyCode === RIGHT_ARROW||keyCode === 68) {
        right();
        
        if (keyCode === UP_ARROW) {
        up()
      } else if (keyCode === DOWN_ARROW) {
        down()
      }
    }
    

    the if statements for UP_ARROW and DOWN_ARROW are inside the if statements for RIGHT_ARROW, when they shouldn't be. Here is a version I cleaned up for you, you can just copy the code and moving should work fine.