Can someone please help me with making the ball bounce off of the black square? I have been at this for days and have gotten nowhere
here
int x, y,
vx, vy;
int r=20;
void setup() {
size(200, 200);
x = (int)random(93, 180);
y = (int)random(93, 170);
vx = (int)random(1, 3);
vy = (int)random(1, 3);
}
void draw() {
background(255);
//display
fill(0);
rect(0, 0, 80, 80);
int sx=0, sy=0, sw=80, sh=80;
// move
x += vx;
y += vy;
// walls
if (x < 10 || x > width - 10)
vx = -vx;
if (y < 10 || y > height - 10)
vy = -vy;
// ellipse
fill(0);
ellipse(x, y, r, r);
// check for collision
// if hit, change rectangle color
boolean hit = circleRect(x, y, r/2, sx, sy, sw, sh);
if (hit) {
reflect (x, y, r, sx, sy, sw, sh);
}
}
// ---------------------------------------------
//
// CIRCLE/RECTANGLE
boolean circleRect(float cx, float cy,
float radius,
float rx, float ry,
float rw, float rh) {
// temporary variables to set edges for testing
float testX = cx;
float testY = cy;
// which edge is closest?
if (cx < rx) {
testX = rx; // test left edge
} else if (cx > rx+rw) {
testX = rx+rw; // right edge
}
//
if (cy < ry) {
testY = ry; // top edge
} else if (cy > ry+rh) {
testY = ry+rh; // bottom edge
}
// get distance from closest edges
float distX = cx-testX;
float distY = cy-testY;
float distance = sqrt( (distX*distX) + (distY*distY) );
// if the distance is less than the radius, collision!
if (distance <= radius) {
return true;
}
return false;
}
// CIRCLE/RECTANGLE
void reflect(float cx, float cy,
float radius,
float rx, float ry,
float rw, float rh) {
// temporary variables to set edges for testing
float testX = cx;
float testY = cy;
// which edge is closest?
if (cx < rx) {
testX = rx; // test left edge
vx = -vx;
} else if (cx > rx+rw) {
testX = rx+rw; // right edge
vx = -vx;
}
//
if (cy < ry) {
testY = ry; // top edge
vy = -vy;
} else if (cy > ry+rh) {
testY = ry+rh; // bottom edge
vy = -vy;
}
}
//