How to animate an Image?

Hello,

my question is how to animate an moving object. In my code I can move Mario and added the animation. But it is at 60 fps by default so its really fast. When I cap the FPS the animation obviously is slower but also my character movement is, which i dont want. Any help to solve this?

int xpos = 200;
int ypos = 700;
int speed = 5;
boolean wKey, aKey, sKey, dKey;
PImage character;
PImage[] animation = new PImage[3];
int animationCase = 0;

void setup(){
  size(1000,1000);
  character = loadImage("MarioStanding.png");
  animation[0] = loadImage("MarioMoving1.png");
  animation[1] = loadImage("MarioMoving2.png");
  animation[2] = loadImage("MarioMoving3.png");
}
void draw(){
  refresh(animationCase);
  animationCase++;
  if(wKey == true){
    if(ypos > 0){
      ypos-=speed;
    }
  }
  if(sKey == true){
    if(ypos < height-character.height){
      ypos+=speed;
    }
  }
  if(dKey == true){
    if(xpos < width-character.width){
      xpos+=speed;
    }
  }
  if(aKey == true){
    if(xpos > 0){
      xpos-=speed;
    }
  }
  if(animationCase == 3){
    animationCase = 0;
  }
}
void refresh(int animationValue){
  background(0,0,0);
  image(animation[animationValue],xpos,ypos,character.width,character.height);
}
void keyReleased(){
  if(key == 'w'){
    wKey = false;
  }
  if(key == 'a'){
    aKey = false;
  }
  if(key == 's'){
    sKey = false;
  }
  if(key == 'd'){
    dKey = false;
  }
}
void keyPressed(){
  if(key == 'w'){
    wKey = true;
  }
  if(key == 'a'){
    aKey = true;
  }
  if(key == 's'){
    sKey = true;
  }
  if(key == 'd'){
    dKey = true;
  }
}

you need to decouple the animation from the display rate. it is a good idea to create an animation class which contains its own animation properties. this example is for p5js and isn’t in a class structure but you can see how a spritesheet is loaded and an independent animation fps is generated. if you search for programming sprite animation class i’m sure you will find something that will assist. Best of luck.

EDIT: i found a really good post on building an animation class i used once i hope it’s helpful.