xxxxxxxxxx
//Variables
int numCircs = 50;
//Speed
float [] speedx = new float [numCircs];
float [] speedy = new float [numCircs];
//Button
float rectX, rectY, rectW, rectH;
//Ball
float ballW, ballH; //ballX, ballY,
// Location
float [] ballXpos = new float [50]; //# of balls I want
float [] ballYpos = new float [50]; //# of balls I want
// ball touched the button?
boolean button = false;
//true? ball color changes
int ballsColor;
void setup () {
size (400, 400);
//button atttributes
rectY = height/2;
rectW = 100;
rectH = 20;
//location of all the balls
for (int i = 0; i < ballXpos .length; i = i++) {
ballXpos[i] = random(width);
speedx[i]=2;
}
for (int i = 0; i < ballYpos .length; i = i++) {
ballYpos[i] = random(height);
speedy[i]=2;
}
}
void draw () {
background (0);
// Effect of Button:
// 1. change ball color when button is touched
if (button == true) {
fill(ballsColor);
} else {
// if no touch stays same
fill(255);
}
//counter
for (int c = 0; c <50; c = c+1) {
fill (ballsColor);
ellipse (ballXpos[c],ballYpos[c],30,30);
if((ballXpos[c]< width) || (ballYpos[c] < height) || (ballXpos[c] <50)||(ballYpos[c]<50)){
// ball bouncing off button and sides screen
if ( (ballXpos[c] > width) || (ballXpos[c] < 0) ) {
speedx[c] = speedx[c] * -1;
if ( (ballYpos[c] > height) || (ballYpos[c] < 0) ) {
speedy[c] = speedy[c] * -1;
}
}
}
}
//BUTTON
rectX = mouseX;
fill (#FCD805); // yellow
rect (rectX, rectY, rectW, rectH);
for (int i = 0; i < ballYpos.length; i++) {
// Draw the balls at random locations
fill(255); //white
ellipse ( ballXpos[i], ballYpos[i], ballW, ballW);// generate new balls
// make them move
ballYpos[i] = ballYpos[i] + speedy[i];
ballXpos[i] = ballXpos[i] + speedx[i];
// hit detection for the Button - Checks if any ball touches the button
if ((ballXpos[i] > rectX-ballW) && (ballXpos[i] < rectX+rectW+ballW) && (ballYpos[i] > rectY-ballW) && (ballYpos[i] < rectY+rectH+ballW)) {
button = !button;
// When any ball hits the button make it bounce in opposit direction
if ( ( ballYpos[i] < rectY) || ( ballYpos[i] > rectY+rectH)) { //if it reaches top or bottom, reverse directions
speedy[i] = speedy[i] * -1; //reverse direction vertically
//make them bounce randomly around
} else if ((ballXpos[i] < rectX) || (ballXpos[i] > rectX+rectW)) { // if it reaches the sides, reverse directions
speedx[i] = speedx[i] * -1; // reverse direction horizontally
}
}
}
}