xxxxxxxxxx
// experimenting with hit detection //
// how many circles
int numCircs = 20;
// how fast on the x and y coordinates
float [] SpeedY = new float [numCircs];
float [] SpeedX = new float [numCircs];
// location of the cirlces
float [] Ypos = new float [numCircs];
float [] Xpos = new float [numCircs];
// Variables to draw the button
float buttonX, buttonY, buttonW, buttonH, ballW;
// if cirlces touch the button
boolean button = false;
void setup() {
size (500, 500);
// button in center
buttonY = height/2;
buttonH = 40;
buttonW = 40;
// Size of all Circles
ballW = 17;
// circles start at random points on the canvas for x and y coordinates
// Ypos.length = how long is list
for (int cat = 0; cat < Ypos.length; cat++) {
Ypos[cat] = random(height);
SpeedY[cat] = 2;
}
for (int cat = 0; cat < Xpos.length; cat++) {
Xpos[cat] = random(width);
SpeedX[cat] = 2;
}
}
void draw() {
buttonX = mouseX;
//Effect on button:
//1. Change background when button is touched
if (button) {
background (0); //black
} else {
background (255, 0, 0);
}
// Draw the button
rect(buttonX, buttonY, buttonW, buttonH);
// Move balls and check hit detection against the button & sides
// Use a for loop to cycle through the arrays i++ = i+1
for (int cat = 0; cat < numCircs; cat++) {
// Draw the balls at random locations
fill(#93888C); // gray
ellipse ( Xpos[cat], Ypos[cat], ballW, ballW);// generate new balls
// when using Xpos, there has to be a [] after it
// make them move
Ypos[cat] = Ypos[cat] + SpeedY[cat];
Xpos[cat] = Xpos[cat] + SpeedX[cat];
// hit detection for the Button - Checks if any ball touches the button
if ((Xpos[cat] > buttonX-ballW) && (Xpos[cat] < buttonX+buttonW+ballW) && (Ypos[cat] > buttonY-ballW) && (Ypos[cat] < buttonY+buttonH+ballW)) {
button = !button;
// When any ball hits the button make it bounce in opposit direction
if ( ( Ypos[cat] < buttonY) || ( Ypos[cat] > buttonY+buttonH)) { //if it reaches top or bottom, reverse directions
SpeedY[cat] = SpeedY[cat] * -1; //reverse direction vertically
//make them bounce randomly around
}
if ((Xpos[cat] < buttonX) || (Xpos[cat] > buttonX+buttonW)) { // if it reaches the sides, reverse directions
SpeedX[cat] = SpeedX[cat] * -1; // reverse direction horizontally
}
}
//if it hits the walls (top - bottom), reverse
if (( Ypos[cat]>height) || ( Ypos[cat]<0)) {
SpeedY[cat] = SpeedY[cat] * -1;
}
//if it hits the walls (sides), reverse
if ((Xpos[cat]>width) || (Xpos[cat]<0)) {
SpeedX[cat] = SpeedX[cat] * -1;
}
}
}