Processing: Trying to create stop motion animation with array of images

2k views Asked by At

I'm trying to create a stop motion animation in processing using 19 images. The only image it shows is the last one in the array which then I thought it must be because of the framerate it would load all 19 in one second, so I tried putting the framerate to "1" with no luck. I then added an if statement to tell the counter to start over and repeat the animation. Any help greatly appreciated.

PImage[] images = new PImage[20];

void setup() {
  size(280, 120);

  for ( int i = 0; i < images.length; i++ )
  {
    images[i] = loadImage(i + ".jpg" );
  }
}

void draw() {
  frameRate(1);
  for (int i = 0; i < images.length; i++)
  {
    image(images[i], 0, 0);
    if (i == images.length-1) {
      i = 0;
    }
  }
}
1

There are 1 answers

2
Matt Coubrough On BEST ANSWER

In Processing draw() is called at the framerate specified in the frameRate() call, which only needs to be called once in your setup() method. In your code, the whole loop from i=0 to images.length runs through in its entirety on every draw call. Thus you only see the last image after every draw().

Instead, create a global variable outside the draw method for the image number you want to show and increment it in the draw method like so:

PImage[] images = new PImage[20];
int frameNum = 0;

void setup() {
    size(280, 120);

    for ( int i = 0; i < images.length; i++ ) {
        images[i] = loadImage(i + ".jpg" );
    }

    frameRate(30);
}

void draw() {

    frameNum++;
    frameNum %= images.length;    
    image(images[frameNum], 0, 0);
}

Explanation

  • When the processing sketch is first run, the int frameNum is set to 0.
  • draw() is called once per frame, and on each call we increment frameNum.
  • Then we ensure frameNum is set to 0 when it is > images.length with frameNum %= images.length