Move with keyboard arrows

hello i am new here,i need help with this code because the thing that i try to move don’t do that, but if i leave one of the if/else statement the code run without problems.
can you help me?
(sorry for the bad english)

if (key == CODED) {
if (keyCode == UP) {
location.y--;
}else if (keyCode == DOWN) {
location.y++;
}else if (keyCode == RIGHT) {
location.x++;
}else{
location.x--;
}
}
1 Like

Hi,

Welcome to the community! :slight_smile:

Remember that you can press Ctrl+T in the Processing IDE to format your code (correct indentation).

I just tested your code and it seems to work fine, I didn’t understand your problem :

// The location of the player
PVector location;

// The speed of the player
int speed = 5;

void setup() {
  size(500, 500);
  
  // Initialize the location in the middle of the window
  location = new PVector(width/2, height/2);
}

void draw() {
  background(255);
  
  // Fill red
  fill(255, 0, 0);
  
  // Draw the ellipse at that location
  ellipse(location.x, location.y, 50, 50);
}

void keyPressed() {
  // Handle arrow keys
  if (key == CODED) {
    if (keyCode == UP) {
      location.y -= speed;
    } else if (keyCode == DOWN) {
      location.y += speed;
    } else if (keyCode == RIGHT) {
      location.x += speed;
    } else if (keyCode == LEFT) {
      location.x -= speed;
    }
  }
}

arrow_ball

1 Like

thank you for the help, i have found the problem is that i have forget to add a variable speed

1 Like