Recitation 7: Functions and Arrays (November 6, 2019) by Jackson McQueeney

In step 1 of this recitation, I drew a single object.

In step 2, I wrote a for loop to draw the same object 100 times. When that for loop was in the setup(), it did this:

When the same for loop was in the draw(), it did this:

In step 3, I stored the data for the locations of the objects and their color in arrays. I did not store the data for the size of the objects as arrays, because I wanted the objects to all be of the same size. 

In step 4, I made each object able to move independently of one another, and they “bounced” when they hit any side of the canvas. The following video shows the final product of the code:

And the final code: 

int NOI = 100;

float x = 100;
float y = 50;

color[] c = new color[NOI];

float xspeed[] = new float [NOI];
float yspeed[] = new float [NOI];
float[] xloc = new float[NOI];
float[] yloc = new float[NOI];

void setup(){
size(600, 600);
background(0);
for(int index = 0; index < NOI; index++) {
  xloc[index]=random(width);
  yloc[index]=random(height);
  c[index]=color(random(255), random(255), random(255));
  xspeed[index]=random(-3, 3);
  yspeed[index]=random(-3, 3);
 }
}

void draw() {
  fill (0);
  rect (0, 0, height, width);
  for(int index = 0; index < NOI; index++) { 
  display(100, 50, xloc[index], yloc[index], c[index]);
  xloc[index]=xloc[index]+xspeed[index];
  yloc[index]=yloc[index]+yspeed[index];
  if (xloc[index]>width || xloc[index]<0){
    xspeed[index]=-xspeed[index];
  }
   if (yloc[index]>width || yloc[index]<0){
    yspeed[index]=-yspeed[index];
  }
  } 
 }

void display(float x, float y, float xloc, float yloc, color c) {
  fill (255);
  ellipse (xloc, yloc, x, y);
  fill (c);
  ellipse (xloc, yloc, x-50, y);
  fill (0);
  ellipse (xloc, yloc, x-80, y-30);
  fill (255);
  ellipse (xloc+10, yloc-10, x-90, y-40);
}

Question 1:
Having the for loop in setup() made each object draw just once. Having the for loop in draw() made each object redraw constantly over previous objects, resulting in the attached video under step 2.

Question 2:
Arrays allow you to create and store a large number of objects in a code. A project that required a random selection among and the storage of many objects would benefit from the use of arrays, as in this project, where arrays were used to store color data as well as x and y location data.

Leave a Reply