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 [numCircs]; //# of balls I want
float [] ballYpos = new float [numCircs]; //# of balls I want
// ball touched the button?
boolean button = false;
void setup () {
size (400, 400);
//button atttributes
rectY = height/2;
rectW = 100;
rectH = 20;
//location of all the balls
// ballXpos.length is the same as numCircs
for (int i = 0; i < ballXpos.length; i = i+1) {
ballXpos[i] = random(width);
speedx[i]=2;
}
// either i++ or i = i + 1never both!
for (int i = 0; i < ballYpos.length; i = i+1) {
ballYpos[i] = random(height);
speedy[i]=2;
}
ballW = 40;
ballH = 40;
}
void draw () {
//BUTTON
//background (0);
if (button == true) {
background(30, 150, 7);
rect (width/2, height/2, 60, 60);
} else {
// if no touch stays same
background(255);
}
rectX = mouseX;
fill (#FCD805); // yellow
rect (rectX, rectY, rectW, rectH);
//counter
//noFill();
for (int c = 0; c < numCircs; c = c+1) {
fill (255, 0, 0);
ellipse (ballXpos[c], ballYpos[c], 30, 30);
ballYpos[c] = ballYpos[c] + speedy[c];
ballXpos[c] = ballXpos[c] + speedx[c];
// is the ball touching the button?
if ((ballXpos[c] > rectX-ballW/2) &&
(ballXpos[c] < rectX+rectW+ballW/2) &&
(ballYpos[c] > rectY-ballW/2) &&
(ballYpos[c] < rectY+rectH+ballW/2)) {
button = !button;
// When any ball hits the button make it bounce in opposit direction
if ( ( ballYpos[c] < rectY) || ( ballYpos[c] > rectY+rectH)) { //if it reaches top or bottom, reverse directions
speedy[c] = speedy[c] * -1; //reverse direction vertically
//fill (0, 0, 255); // testing changing the ball colour on button presss
//make them bounce randomly around
} else if ((ballXpos[c] < rectX) || (ballXpos[c] > rectX+rectW)) { // if it reaches the sides, reverse directions
speedx[c] = speedx[c] * -1; // reverse direction horizontally
//fill (255, 0,0);
}
}
// is the ball touching the sides
if ( (ballXpos[c] > width) || (ballXpos[c] < 10) ) {
speedx[c] = speedx[c] * -1;
}
// is the ball touching the top or bottom?
if ( (ballYpos[c] > height) || (ballYpos[c] < 10) ) {
speedy[c] = speedy[c] * -1;
}
}
}