Array of keys. Movement

Hello, what is wrong with this code? Why player (black square) wont move in 4 directions, but only in 2.

Postac postac = new Postac();

boolean[] chodzenie = new boolean[4];              //UP DOWN LEFT RIGHT
/*                                                   0  1    2    3    */


void setup() {
  size(600, 600, P2D);

  for (int i = 0; i < chodzenie.length; i++) {
    chodzenie[i] = false;
  }
 
  postac.location = new PVector(width/2, height/2);
  postac.velocity = new PVector(0, 0);

}

void draw() {
  background(190);

  postac.display();
  postac.chodzenie();
}

void keyPressed() {

  if (key == CODED && keyCode == UP)    chodzenie[0] = true;
  if (key == CODED && keyCode == DOWN)  chodzenie[1] = true;
  if (key == CODED && keyCode == LEFT)  chodzenie[2] = true;
  if (key == CODED && keyCode == RIGHT) chodzenie[3] = true;
}

void keyReleased() {

  if (key == CODED && keyCode == UP)    chodzenie[0] = false;
  if (key == CODED && keyCode == DOWN)  chodzenie[1] = false;
  if (key == CODED && keyCode == LEFT)  chodzenie[2] = false;
  if (key == CODED && keyCode == RIGHT) chodzenie[3] = false;
}

void mousePressed() {
}

class Postac {

  PVector location, velocity;
  int a = 20;

  void display() {
    fill(0);
    rect(location.x, location.y, a, a);
    location.add(velocity);

    println("0" + chodzenie[0] + " 1" + chodzenie[1] + " 2" + chodzenie[2] + " 3" + chodzenie[3]);
    println(velocity);
  }


  void chodzenie() {

    if (chodzenie[0] == true) {
      velocity.y = -1;
    } else if (chodzenie[0] == false) {
      velocity.y = 0;
    }

    if (chodzenie[1]) { 
      velocity.y =  1;
    } else if (!chodzenie[1]) {
      velocity.y = 0;
    }

    if (chodzenie[2]) { 
      velocity.x = -1;
    } else if (!chodzenie[2]) {
      velocity.x = 0;
    }

    if (chodzenie[3]) { 
      velocity.x =  1;
    } else if (!chodzenie[3]) {
      velocity.x = 0;
    }
  }
}

It is because of your logic in your chodzenie() function. Think about the following lines of code:

    if (chodzenie[0] == true) {
      velocity.y = -1;
    } else if (chodzenie[0] == false) {
      velocity.y = 0;
    }

    if (chodzenie[1]) { 
      velocity.y =  1;
    } else if (!chodzenie[1]) {
      velocity.y = 0;
    }

Can you spt the problem? Imagine yu press UP and then DOWN. Then imagine when you do the opposite: your press DOWN and then you press UP.

I am certain you will catch the bug by looking at these lines.

Kf

1 Like

Of course!! Thanks a lot.

    if (chodzenie[0]) 
      velocity.y = -1;
    if (chodzenie[1]) 
      velocity.y =  1;
    if (chodzenie[2]) 
      velocity.x = -1;
    if (chodzenie[3]) 
      velocity.x =  1;

    if (!chodzenie[0] && !chodzenie[1]) velocity.y = 0;
    if (chodzenie[0] && chodzenie[1])   velocity.y = 0;
    if (!chodzenie[2] && !chodzenie[3]) velocity.x = 0;
    if (chodzenie[2] && chodzenie[3])   velocity.x = 0;```