xxxxxxxxxx
boolean buttonhit = false;
int x2 = 250;
int y2 = 150;
int speedY = 3; // top and bottom
int speedX = 3; // left and right
float rectX, rectY, rectW, rectH; //button
void setup() {
size (500,500);
rectX = 250;
rectY =250;
rectW =100;
rectH =100;
}
void draw() {
background (100,100,100);
if (buttonhit == true) {
background (255, 245, 175); // yellow
} else {
buttonhit = false;
}
fill (255, 186, 251);
ellipse (x2,y2, 40,40);
y2 = y2 + speedY;
x2 = x2 + speedX;
//top to bottom
if ((y2-10 > height) || (y2+10 < 0)){
speedY = speedY * -1;
}
//left to right
if ((x2-10 > width) || (x2+10 < 0)) {
speedX = speedX * -1;
}
// hit detection of ball to button.
if ((y2+ 10 >= rectY) &&
(x2-10 <= rectX + rectW) &&
(x2+10 >= rectX) &&
(y2-10 <= rectY+rectH)) {
if (x2 < rectX){
speedX = speedX * -1;
} else if (x2 > rectX+rectW){
speedX = speedX * 1;
} if (y2 < rectY) {
speedY = speedY * -1;
} else if (y2 > rectY+rectH){
speedY = speedY * 1;
}
buttonhit = !buttonhit;
}
fill (0);
rect (rectX,rectY,rectW,rectH);
}