/* * A demonstration of the use of arrays to allow for repainting * the canvas (with modification). In this sketch, we draw randomly * placed circles and allow the user to change the color of a circle * with a mouse click. We take care to make sure that when circles * overlap, a mouse click only changes the one that is visible at * the mouse location. * * Pressing the 's' key will reshuffle the scene. * * Author: Michael Goldasser */ int N = 100; // total number of circles int R = 25; // fixed radius for all circles float x[] = new float[N]; // x[j] is x-coordinate of circle j float y[] = new float[N]; // y[j] is y-coordinate of circle j color c[] = new color[N]; // c[j] is color of circle j void setup() { size(600, 400); shuffle(); // pick initial parameters } // pick initial circle locations and colors void shuffle() { for (int j=0; j < N; j++) { x[j] = random(width); y[j] = random(height); c[j] = color(random(255), random(255), random(255)); } } void draw() { // we begin by clearing the canvas before repainting // (although unnecessary for this particular application) background(255); // draw each circle in its current color, going from 0 to N-1 for (int j=0; j < N; j++) { fill(c[j]); ellipse(x[j], y[j], 2*R, 2*R); } } void mouseClicked() { // determine which circle (if any) is being clicked upon. // intentionally search from greatest index to least, to find // the circle that is on top of any overlapping area for (int j=N-1; j >=0; j--) { float distSquared = (mouseX-x[j])*(mouseX-x[j]) + (mouseY-y[j])*(mouseY-y[j]); if (distSquared <= R*R) { c[j] = color(random(255), random(255), random(255)); break; // quit out of for loop to avoid obscured changes } } } void keyPressed() { if (key == 's') { shuffle(); } }