xxxxxxxxxx
//-------- Variables
float rectX, rectY, rectW, rectH; // Button
float bX, bY, bW, bRad; // Bouncing ball
float bSpeedX, bSpeedY; // Ball speed on X and Y axis respectively
boolean buttonClicked = false; // checks if button has been "clicked" or touched or not
void setup () {
size (400, 400);
// Button size, location etc.
rectX = width/2;
rectY = height/2;
rectW = 180;
rectH = 20;
// Ball size, starting location etc.
bX = 20;
bY = height/2;
bW = 18;
bRad = bW/2;
// Speed of Ball on Y and X axis, can be any number you want
bSpeedY = 3.5;
bSpeedX = 3.5;
}
void draw () {
background (255); // background is initially white
// checks if "button is clicked", which means checks if rectangle is touched by ball
if (buttonClicked == true) {
background (152, 133, 155); // changes the Background to purple
} else {
buttonClicked = false;
}
// ball bouncing off button and sides screen
// NOTE: we add / subtract bRad as it is 1/2 the width, which is the radius, allowing only the edge of the ball to touch the sides
if ( (bY+bRad > height) || (bY-bRad < 0) ) {
bSpeedY = bSpeedY * -1;
}
if ( (bX+bRad > width) || (bX-bRad < 0) ) {
bSpeedX = bSpeedX * -1;
}
// hit detection of ball to button. checks if ball touches the yellow button in the middle
if ( (bY+bRad >= rectY) && // is Ball touching the top
(bX-bRad <= rectX + rectW) && // is ball touching the right side
(bX+bRad >= rectX) && // is ball touching the left side
(bY-bRad <= rectY+rectH) ) // is ball touching the bottom
{ // if ALL the above conditions are met, ONLY THEN do the following
if (bX < rectX) { // when greater than left side of button (hits left side)
bSpeedX = -3.5; // change direction on X axis, (ball bounces left)
bX = rectX - bRad;
} else if (bX > rectX + rectW) { // or else when greater than right side of button (hits right side)
bSpeedX = 3.5; // change direction on X axis (ball bounces right )
bX = rectX + bRad;
} else if (bY < rectY) { // oe else when its less than top (hits top)
bSpeedY = -3.5; // change direction on Y axis, (ball bounces up)
bY = rectY - bRad;
} else if (bY > rectY + rectH) { // or else when its greater than bottom (hits bottom)
bSpeedY = 3.5; // change direction on Y axis (ball bounces down)
bY = rectY +rectH + bRad;
}
buttonClicked = !buttonClicked; // this allows the change in BG to remain till the ball touches the yellow button again
}
fill (#FCD805); // button is yellow
rect (rectX, rectY, rectW, rectH);
fill (#FA0848); // ball is red
ellipse (bX, bY, bW, bW);
bY = bY + bSpeedY; // ball moves on down
bX = bX + bSpeedX; // ball moves right
}