xxxxxxxxxx
//number of balls
int circlenum = 50;
float [] SpeedY = new float [circlenum];
float [] SpeedX = new float [circlenum];
//location of circles
float [] posY = new float [circlenum];
float [] posX = new float [circlenum];
//variables for button
float buttonX, buttonY, buttonW, buttonH, ballW;
//whether ball has touched the button
boolean button = false;
void setup () {
size (500,400);
buttonX = width/3+40;
buttonY = height/2-20;
buttonH = 50;
buttonW = 100;
//circle sizes
ballW = 10;
for (int i = 0; i < posY.length; i++) {
posY[i] = random(height);
SpeedY[i] = 2;
}
for (int i = 0; i < posX.length; i++) {
posX[i] = random(height);
SpeedX[i] = 2;
}
}
void draw () {
//button effect
if (button) {
background (255, 201, 254); //light pink
} else {
background (250,250,250); //change background
}
//draw button
fill (179, 117, 249); //purple
rect (buttonX, buttonY, buttonW, buttonH);
//move balls and check hit detection
for (int i = 0; i < posY.length; i++) {
//draw balls at random location
fill (150, 211, 255); //light blue
ellipse (posX[i], posY[i], ballW, ballW); //generate balls
//make the balls move
posY[i] = posY[i] + SpeedY[i];
posX[i] = posX[i] + SpeedX[i];
//hit detection for button
if ( (posX[i] > buttonX-ballW) && (posX[i] < buttonX+buttonW+ballW) && (posY[i] > buttonY-ballW) && (posY[i] < buttonY+buttonH+ballW) ) {
button = !button;
//when balls hit button make bounce in opposite direction
if ( (posY[i] < buttonY) || (posY[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 ( (posX[i] < buttonX) || (posX[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 ( (posY[i] > height) || (posY[i] < 0) ) {
SpeedY[i] = SpeedY[i] * -1;
}
//if it hits the walls (sides), reverse
if ( (posX[i] > width) || (posX[i] < 0) ) {
SpeedX[i] = SpeedX[i] * -1;
}
}
}