The ‘for’ Loop

icm03-forloop

Loops are used to execute a block of code a number of times, with different values. In this case, I used the ‘for’ loop functionality to create a grid of elements.

(int x = -50; x < width; x+=50) refers to the X position of certain type of element. It starts in pixel -50 and ends in the screen width, displaying a different element each 50 pixels.
Each element is a triangle whose first edge is located in X and Y, the second one is located in Y+var, and the third one responds to the mouse position.

The resulting sketch displayed some colorful 3d rays, so I decided to add another 3d element to improve this idea.

Processing code:

float ax=350; float ay=390; void setup() { size(800, 800); colorMode(HSB); frameRate(10); } void draw() { background(0); for (int x = -50; x < width; x+=50) { for (int y = -50; y < height; y+=50) { fill( random(255), 100, 255, 50); float var=random(10, 100); if (mousePressed) { fill( random(255), 50); frameRate(60); } else {frameRate(10);} noStroke(); triangle(mouseX, mouseY, x, y+var, x+var, y+var); } } // 3D Shape stroke(255); fill(0,200); rect(ax, ay, 100, 20); // left & right triangles if (mouseX >= 450) { triangle(mouseX, mouseY, ax+100, ay+20, ax+100, ay); } else if (mouseX <= 350) { triangle(mouseX, mouseY, ax, ay, ax, ay+20); } // top & bottom triangles if (mouseY >= 410) { triangle(mouseX, mouseY, ax,ay+20,ax+100,ay+20); } else if (mouseY <= 390) { triangle(mouseX, mouseY, ax,ay,ax+100,ay); } }

Leave a Reply