Change variable alternatingly

how to change i to 2 every couple of seconds/frames and then back

  direction[1]= loadImage("left.png");
  direction[2]= loadImage("right.png");

 i;

void setup(){
fullScreen();
}
void draw(){
image(direction[i], imagex, height-(height/4), 50, 80);
}
1 Like

I think you already have a good starting point. The easier way is to use frameCount. You can use modulus to “cycle” the frame count, for example frameCount % 60 would return 0 to 59, and then repeats from 0. According to that value, change i from 1 to 2… I guess that’s enough to make it happen :slight_smile:

this does not work. did i do something wrong?

 PImage[] direction= new PImage[3];
 int i=1;

void setup(){
fullScreen();
  direction[1]= loadImage("left1.png");
  direction[2]= loadImage("right.png");
}
void draw(){
  if(frameCount % 60==29){
  i=2;}
  if(frameCount % 60==0){
  i=1;}
image(direction[i], imagex, height-(height/4), 50, 80);
}

Hi @MoonAlien822
That should totally work… when I test it here it works fine. One little tweak, perhaps you’re doing it for a reason, but why make the direction array of size 3?

PImage[] directionImages = new PImage[2];
int directionIndex = 0;

void setup() {
  size(600, 600);
  directionImages[0]= loadImage("left1.png");
  directionImages[1]= loadImage("right.png");
}
void draw() {
    
  if(frameCount%60 == 0) {
    directionIndex = 0;
  }
  if(frameCount%60 == 29) {
    directionIndex = 1;
  }

  image(directionImages[directionIndex], 0, 0, width, height);
}

1 Like

for my head its easier to work with numbers higher than 0 when counting. arrays start at 0, so while im only using 1 and 2, there are still three

1 Like

Haha okay… you do you! But did you get it to work??

yes i did! It works in my full code too, thank you so much

1 Like

i would like to make the time way longer, how do i know what to set it to?

It’s the “60” in frameCount%60. The frame count increases at the frame rate the sketch is set to, which by default is 60. The % operator gives you “the remains” of dividing the number by 60, which means that frameCount%60 will count from 0 to 59 every second. If you set it to a larger amount (120 would be two seconds), you’d increase the interval.

1 Like