Diagonal move not working

//clase jugador--------------------------------------
class Jugador extends Padre{
  private float x,y,velocidad;
  private PImage grafico = loadImage("jugador.png");
  private Disparo disparo1;
  private int contador; 
  
  public Jugador(){
    super();
    imageMode(CENTER);
    this.x = 320;
    this.y = 400;
    this.velocidad = 5;
    this.contador = 0;
  }
  
  public void draw(){
    mover();
    disparar();
    image(grafico,x,y);
  }
  
  private void mover(){
    if(keyPressed && key == CODED && keyCode == LEFT){
      x -= velocidad;
    }else if(keyPressed && key == CODED && keyCode == RIGHT){
      x += velocidad;
    }
    
    if(keyPressed && key == CODED && keyCode == UP){
      y -= velocidad;
    }else if(keyPressed && key == CODED && keyCode == DOWN){
      y += velocidad;
    }
  }
  
  private void disparar(){
    contador++;
    if(keyPressed && key == 'z' && contador > 5){
      disparo1 = new Disparo(x,y); 
      contador = 0;
    }
  }

} //fin clase jugador------------------------------------

In the move method I am moving the player with the keys but if I press two keys like up and left it does not move diagonally, as it would.

Hi, its because keyPressed only recognizes the last key pressed, there is a solution with ArrayList that works great, ill just post the code I came up with that works fine, just have a look through it and see how you could use that in your class

ArrayList<Integer> keys = new ArrayList<Integer>();

PVector pos;
int radius = 15;

void setup() {
  size(600, 600);
  pos = new PVector(width/2, height/2);
}

void draw() {
  background(0);

  controls();

  noStroke();
  circle(pos.x, pos.y, radius*2);
}

void controls() {
  int speed = 5;
  if (keys.contains(UP)) pos.add(new PVector(0, -speed));
  if (keys.contains(DOWN)) pos.add(new PVector(0, speed));
  if (keys.contains(LEFT)) pos.add(new PVector(-speed, 0));
  if (keys.contains(RIGHT)) pos.add(new PVector(speed, 0));

  //if space pressed
  if (keys.contains(32)) { // keycode for space
    fill(255, 0, 0);
  } else fill(255);

  pos.x = constrain(pos.x, radius, width-radius);
  pos.y = constrain(pos.y, radius, height-radius);
}

void keyPressed() {
  //println(keyCode); use this to find the specific key code you want
  if (!keys.contains(keyCode)) keys.add(keyCode);
}

void keyReleased() {
  keys.remove(keys.indexOf((keyCode)));
}
2 Likes

Thank you very much for the help Mikey83, it works perfectly. :wink:

1 Like

Awesome then, could you mark it as a solution mate, thanks