Created
June 16, 2014 16:02
-
-
Save PDMackinnon/62a309ad0ef13cfe3c2c to your computer and use it in GitHub Desktop.
Future Learn creative coding exercise - start/stop oscillating circles by mouse click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Creative Coding | |
* Week 3, 02 - array with sin() | |
* by Indae Hwang and Jon McCormack | |
* Copyright (c) 2014 Monash University | |
* | |
* This program demonstrates the use of arrays. | |
* It creates three arrays that store the y-position, speed and phase of some oscillating circles. | |
* You can change the number of circles by changing the value of num in setup() | |
* You can change the background colour by holding the left mouse button and dragging. | |
* | |
*/ | |
int num; // the number of items in the array (# of circles) | |
float[] y; // y-position of each circle (fixed) | |
float[] x; | |
float[] speed; // speed of each circle | |
float[] phase; // phase of each circle | |
boolean[] stopped; | |
float red = 120; | |
float green = 120; | |
float blue = 120; | |
void setup() { | |
size(500, 500); | |
num = 20; | |
// allocate space for each array | |
y = new float[num]; | |
x = new float[num]; | |
speed = new float[num]; | |
phase = new float[num]; | |
stopped = new boolean[num]; | |
// calculate the gap in y based on the number of circles | |
float gap = height / (num + 1); | |
//setup an initial value for each item in the array | |
for (int i=0; i<num; i++) { | |
y[i] = gap * (i + 1); // y is constant for each so can be calculated once | |
speed[i] = random(10); | |
phase[i] = random(TWO_PI); | |
stopped[i] = false; | |
} | |
} | |
void draw() { | |
background(red, green, blue); | |
for (int i=0; i<num; i++) { | |
// calculate the x-position of each ball based on the speed, phase and current frame | |
if (stopped[i]) { | |
// do not update x[i] | |
} else { | |
// running so calc new x: | |
x[i] = width/2 + sin(radians(frameCount*speed[i] ) + phase[i])* 200; | |
} | |
ellipse(x[i], y[i], 40, 40); | |
} | |
} | |
// change the background colour if the mouse is dragged | |
void mouseDragged() { | |
red = map(mouseX, 0, width, 0, 255); | |
green = map(mouseY, 0, height, 0, 255); | |
blue = map(mouseX+mouseY, 0, width+height, 255, 0); | |
} | |
void mouseClicked() { | |
for (int i=0; i<num; i++) { | |
if (dist(mouseX, mouseY, x[i], y[i]) < 40) { | |
// clicked on circle i | |
stopped[i]=!stopped[i]; //toggle on/off | |
}//end if | |
}//end for | |
}//end mouse clicked | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment