8 directional movement in object

I need to make my player move in all of 8 directions using W A S D and my code makes some weird stuff when I press more than one key and I don’t know why

class Vini {

  float x = width/2;
  float y = height/2;
  float vel = 10;
  boolean [] keys = new boolean[128];

  void display() {
    ellipse(x, y, 50, 50);
  }

  void movement() {
    if (keyPressed) {

      keys[key]= true;

      if (keys['w']) {
        y -= vel;
      }
      if (keys['s']) {
        y += vel;
      }
      if (keys['a']) {
        x -= vel;
      }
      if (keys['d']) {
        x += vel;
      }
    } else if (keyPressed == false) {
      keys[key] = false;
    }
  }
}

Vini vini;

void setup() {
 size(600, 600);
 vini = new Vini();
}

void draw() {
  background(50);
  vini.display();
  vini.movement();
}

if anyone could helpme I would be very grateful :+1:

Hello!
I ran your code. Confirming the directional movement is not consistent or as expected on MacOS, processing 4.0.1.

:nerd_face:

Hi @vinijoncrafts,

Move the key handling out of your class…

boolean[] keys = new boolean[255];

void keyPressed() {
  keys[keyCode] = true;
}

void keyReleased() {
  keys[keyCode] = false;
}

Your movement method then should look like…

Cheers
— mnse

2 Likes

then I should put these keypressed/released at the end of the code? If yes, then thank you!

yoooooo it worked thanks a lot!