For this week’s exercise, we worked with arrays and functions, which was a bit more challenging to grasp. Our task was to create 3 objects with 100 arrays and call them. But as I figured out the first one, the other ones became easier.
I used the smiley face code we did in class as a reference and used for loops on top of that. However, then I focused on calling one object, which was the ellipse and commented out the other ellipses and arcs that made the smiley face, which made my final ‘graphic design’ consisting of 3 objects: ellipse, triangle, and rectangle. I used the for loop referenced in the recitation guide and used the symbol n to define numberofInstances, which was 100 arrays. Then, I used the new [] function to move my objects according to speed and randomized their colors to make the exercise more fun. I also used the xloc and yloc functions to help me track the location of the xy axis of the object, which was easier to expand on as the number of objects multiplied.
Code:
int n = 100; float x = 100; float y = 50; color[] c = new color [n]; float xspeed[] = new float[n]; float yspeed[] = new float[n]; float [] xloc = new float[n]; float [] yloc = new float[n]; void setup(){ size(600,600); background(255); for(int index = 0; index < n; index++) { xloc[index]=random(width); yloc[index]=random(height); c[index]=color(random(255), random(255), random(255)); xspeed[index]=random(-10, 5); yspeed[index]=random(-10, 5); } } void draw() { fill (0); rect (0, 0, height, width); for(int index = 0; index < n; index++) { display(100,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(int size, float x, float y, float xloc, float yloc, color c){ //ellipse noStroke(); fill(c); ellipse(xloc,yloc,x,y); fill(0); //rectangle fill(c); rect(xloc-10,yloc+10,x,y); fill(255); //triangle fill (c); triangle(xloc+50, yloc-10, x-90, y-40,0,0); fill(255); }
Video:
Question 1:
I noticed that when I put my loop () in setup, it played only once, whereas when I put my loop() in draw, it looped the objects and repeated on top of what was already drawn.
Question 2:
There are many benefits of using arrays such as collecting and organizing big data, arrays make it a lot easier to see and understand which values are in place. Arrays are also useful when making projects that draw on a lot of data and needs structure, this way, the code is a lot more concise and easy to understand. In a future project, arrays can be used to call on different randomization of animation, like what we did for this exercise. Or, it can be used for map projects, to call on different points of data to display certain points/places on a map.