xxxxxxxxxx
// how many balls do you want?
int numCircs = 51;
// Variables for the Circles
// How fast to move it on the X and Y coordinates
float [] SpeedY = new float [numCircs];
float [] SpeedX = new float [numCircs];
// Location of Circles
float [] Ypos = new float [numCircs];
float [] Xpos = new float [numCircs];
// Variables to draw the button
float buttonX, buttonY, buttonW, buttonH, ballW;
// Has any ball touched the button?
boolean button = false;
void setup () {
size (500, 700);
// align the button to the center of screen
buttonX = width/2-80;
buttonY = height*2/3;
buttonH = 40;
buttonW = 160;
// Size of all Circles
ballW = 7;
// Start the Circles at a different random point on the screen for X and Y coordinates
for (int i = 0; i < Ypos.length; i++) {
Ypos[i] = random(height); // Start on different parts of the sketch (change to a location or i* 5, to make them appear in a line
SpeedY[i] = 2;
}
for (int i = 0; i < Xpos.length; i++) {
Xpos[i] = random (height);
SpeedX[i] = 2;
}
}
void draw () {
// Effect of Button:
// 1. change background when button is touched
if (button) {
background (#9370A5); //purple
// 2. draw a triangle when button is hit
fill (255);
triangle (200, 300, 250, 200, 300, 300);
} else {
background (#FADD00); // Change BG to yellow
}
// Draw the button
fill(#00FAA0);
rect (buttonX, buttonY, buttonW, buttonH);
// Move balls and check hit detection against the button & sides
// Use a for loop to cycle through the arrays
for (int i = 0; i < Ypos.length; i++) {
// Draw the balls at random locations
fill(#93888C); // gray
ellipse ( Xpos[i], Ypos[i], ballW, ballW);// generate new balls
// make them move
Ypos[i] = Ypos[i] + SpeedY[i];
Xpos[i] = Xpos[i] + SpeedX[i];
// hit detection for the Button - Checks if any ball touches the button
if ((Xpos[i] > buttonX-ballW) && (Xpos[i] < buttonX+buttonW+ballW) && (Ypos[i] > buttonY-ballW) && (Ypos[i] < buttonY+buttonH+ballW)) {
button = !button;
// When any ball hits the button make it bounce in opposit direction
if ( ( Ypos[i] < buttonY) || ( Ypos[i] > buttonY+buttonH)) { //if it reaches top or bottom, reverse directions
SpeedY[i] = SpeedY[i] * -1; //reverse direction vertically
//make them bounce randomly around
} else if ((Xpos[i] < buttonX) || (Xpos[i] > buttonX+buttonW)) { // if it reaches the sides, reverse directions
SpeedX[i] = SpeedX[i] * -1; // reverse direction horizontally
}
}
//if it hits the walls (top - bottom), reverse
if (( Ypos[i]>height) || ( Ypos[i]<0)) {
SpeedY[i] = SpeedY[i] * -1;
}
//if it hits the walls (sides), reverse
if ((Xpos[i]>width) || (Xpos[i]<0)) {
SpeedX[i] = SpeedX[i] * -1;
}
}
}