Week 6 – Arrays

What is an array? – Tutorial here.
Declare and initialize and array – See here
How to use an array to animate images – see here

A basic array is a list of data. Each spot in the list is identified by an index number. An array can be set up to hold any data type. (ints, floats, PImages)Arrays are zero based, which means that the first
element in the array is [0], the second element is [1], and so on.

Array.  
//declare array
float[] randomArray; 
 
void setup() {
  size(640, 360);
  //initialise array - setting its length to 10.
  randomArray = new float[10];
 
  //run through each spot in the array (i=0 to i=9)
  for (int i = 0; i < 9; i++) {
    //put a random value in each spot (this will be an x value)
    randomArray[i] = random(0,width);
  }
  background(255);
  //only run through draw once.
  noLoop();
}
 
void draw() {
  //run through each spot in the array
  for (int i = 0; i < 9; i++) {
    fill(200,0,0,100);
    //draw an ellipse using the random value in each spot of the array
    ellipse(randomArray[i], height/2,20,20);
    //print to check what it is
    println(randomArray[i]);
  }
}

The example here uses an array to create an animation and loop through the image frames, you will need to set up a sketch with images labelled cat0.jpg, cat1.jpg, cat2.jpg and cat3.jpg and have them in the data folder of your sketch.

//ARRAY OF IMAGES
//declare data type 
PImage[] images = new PImage[4];  //Array of Pimages - 4 spots long
int j=0;// a variable to call each position in our array
int n=10;
 
void setup(){
  size(300,300);
  //fill our array
 for(int i=0;i<4;i++){ //run through values of i from 0-4
  images[i] = loadImage("cat"+i+".jpg"); //use these values to fill each box in our array
}
}
void draw(){
  //image function
  //image(data, x,y,width,height);
 
  if(j>3){ //if i reach the end of my array
    j=0; //send j back to zero
  }
 
    image(images[j],0,0, width,height); //draw images to screen for each value of j (position in your array)
 
   j++; //j generates values that we then use to call each position of the array
   println(frameRate);
 
}

EXERCISE:
Take your existing stop frame animation and develop it so that you character moves across the screen as it animates. When it leaves the screen make it return on the other side. Can you vary the speed that it moves each time it enters the screen?

'+
1
'+
2 - 3
4 - 5
6 - 7
8 - 9
10 - 11
12 - 13
13 - 14
[x]