/* * 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 drag an individual circle * with a mouse drag. * * 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 int current = -1; // index of circle being drag (or -1 if None) 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 mousePressed() { // determine which circle (if any) is being chosen. // Note that in case multiple circles are under the mouse // we will end up with current being that with greatest index for (int j=0; j < N; j++) { if (dist(mouseX, mouseY, x[j], y[j]) <= R) { current = j; } } } void mouseDragged() { if (current != -1) { x[current] += (mouseX - pmouseX); y[current] += (mouseY - pmouseY); } } void mouseReleased() { current = -1; } void keyPressed() { if (key == 's') { shuffle(); } }