0

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;
    }
  }
}
Ceramicwhite
  • 57
  • 1
  • 6
  • You will need to add timing of some form here. The most basic, which I would recommend for quick testing - just add Thread.sleep() to the loop. After that, you may want to look for a better approach. Not knowing the underlying graphics and UI toolsets involved, I won't make any guesses. Look for animation support. – ash Dec 08 '14 at 22:48
  • @ash Processing has built-in animation support as it is effectively a Java framework for visualisations: https://www.processing.org/ – Matt Coubrough Dec 08 '14 at 23:10

1 Answers1

1

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
Matt Coubrough
  • 3,739
  • 2
  • 26
  • 40
  • Or you could simple use system [frameCount](https://www.processing.org/reference/frameCount.html) and use it like this: `image(images[frameCount % images.length])` – Majlik Dec 09 '14 at 08:42
  • @Majlik good point - although having an independent variable gives you more control if you later decide to pause the animation etc. – Matt Coubrough Dec 09 '14 at 08:49