Functions and Arrays
During the recitation:
Step 1.
We had to create a function to make up a design of our own with at least three different shapes. I made a house, with the a rectangle as a base, a triangle as a roof, a rectangular door and a squared window.
Step 2:
Create a loop to display the function 100 times with a variety of positions and colours.
Step 3:
Create the arrays to make the 100 displayed houses with random positions and random colours and to have little movement:
Step 4
For the last time, I made sure that the movement was staying on the canvas by adding the if condition:
if(xpositions[i] >= width-100) {
xpositions[i]=width-100;
}
if(xpositions[i] <= 0) {
xpositions[i]=0;
}
if(ypositions[i] >= height-100) {
ypositions[i]=height-100;
}
if(ypositions[i] <= 75) {
ypositions[i]=75;
}
The overall code is as followed:
int number = 100; float[] xpositions = new float[number]; float[] ypositions = new float[number]; color[] ccolor = new color[number]; void setup() { size (800, 800); for(int i = 0; i < number; i++) { xpositions[i] = random(width); ypositions[i] = random(height); ccolor[i] = color(random(255), random(255), random(255)); printArray(xpositions); println(); printArray(ypositions); } } void draw() { background(255); for(int i=0; i<xpositions.length; i++) { display(xpositions[i], ypositions[i], ccolor[i]); xpositions[i] += random(-5, 5); ypositions[i] += random(-5, 5); if(xpositions[i] >= width-100) { xpositions[i]=width-100; } if(xpositions[i] <= 0) { xpositions[i]=0; } if(ypositions[i] >= height-100) { ypositions[i]=height-100; } if(ypositions[i] <= 75) { ypositions[i]=75; } } } void display(float x, float y, color c ) { fill(c); triangle(x, y, x+50, y-75, x+100, y); //roof fill(255,175,0); rect(x, y, 100, 100); //house fill(255); rect(x+40, y+70, 20, 30); //door rect(x+70, y+20, 20, 20); //window }
Question 1:
When putting the for loop in Step up in setup() instead of in draw(), the loop only runs once, whereas when I put it in draw(), the loop ran over and over.
Question 2:
The benefit of using arrays is that instead of having many long functions, it can display your design using variables which makes your code much shorter. To do so, it stores values in order to use them later on in the coding. In this way, to change a value, we can just change it at the top, instead of in the entire code.