Home > Net >  How to have multiple images in a sequence when a key is pressed - Processing
How to have multiple images in a sequence when a key is pressed - Processing

Time:01-06

I want to be able to have animate a sprite by using 3 different images when a key is pressed how would I do so, with an array as well as without one.

CodePudding user response:

You can easily repurpose the Processing Animated Sprite example. You'll need one Animation instance and keyPressed() to animate the sprite (e.g. toggle frame updates)

Shameless plug: another option is using a library such as ImageSequencePlayer

CodePudding user response:

If you want to avoid arrays and libraries this technique will work. The frameRate() needs to turned down to 4 or 5 and then place a counter in the draw() which is reset to zero when it exceeds the number of images. As the counter value is passed to a display function it then displays the corresponding image. The images should be placed in a folder titled "data" in the sketch folder.

/*
 Must be GIF, JPEG, or PNG images
 */
PImage img0;
PImage img1;
PImage img2;
PImage img3;
PImage img4;

int counter = 0;

void setup() {
  size(400, 400);
  img0 = loadImage("frog0.png");
  img1 = loadImage("frog1.png");
  img2 = loadImage("frog2.png");
  img3 = loadImage("frog3.png");
  img4 = loadImage("frog4.png");
}

void display(int count) {
  switch(count) {
  case 0:
    image(img0, 0, 0, width, height);
    break;
  case 1:
    image(img1, 0, 0, width, height);
    break;
  case 2:
    image(img2, 0, 0, width, height);
    break;
  case 3:
    image(img3, 0, 0, width, height);
    break;
  case 4:
    image(img4, 0, 0, width, height);
    break;
  }
}

void draw() {
  frameRate(4);
  display(counter);
  counter  ;
  if (counter > 4) {
    counter = 0;
  }
}

  •  Tags:  
  • Related