<> please format code with </> button * homework policy * asking questions
When my ball goes to the top of the rect, It will be put in the center rect. However, I want it bouncing. I don’t know how to fix it. Someone can help me fix it. Thank you.
float ballX;
float ballY;
float ballSpeedX = 4;
float ballSpeedY = 4;
float ballDia = 20.0;
float ballR = ballDia/2;
void setup() {
size(800, 600);
ballX= random(10, 370);
ballY= random(10, 570);
}
void draw() {
background(0);
// Draw the wall
fill(255);
noStroke();
rect(390, 300, 20, 300);
// Color of the ball changes gradually and continuously as it moves
fill(ballX,ballY,ballX%ballY);
// Draw the ball
ellipse(ballX, ballY, ballDia, ballDia);
// Update ball location
ballX=ballX+ballSpeedX;
ballY=ballY+ballSpeedY;
// If ball hit the right or left change direction of X
if (ballX> width- ballR || ballX < ballR) {
ballSpeedX=ballSpeedX*-1;
}
// If ball hit top or bottom change direction of Y
if (ballY> height-ballR || ballY < ballR) {
ballSpeedY=ballSpeedY*-1;
}
// Setup variable to true if shapes are over lapping, false if not
boolean collision = hitWall(390, 300, 20, 300, ballX, ballY, ballR);
// Change ball direction when ball hit
//and bump it back
if (collision ==true) {
ballSpeedX=ballSpeedX*-1;
ballX +=ballSpeedX;
}
}
boolean hitWall(int rx, int ry, int rw, int rh,
float cx, float cy, float cr) {
float circleDistanceX= abs(cx - rx - rw/2);
float circleDistanceY= abs(cy - ry - rh/2);
if (circleDistanceX > (rw/2 + cr)) {
return false;
}
if (circleDistanceY > (rh/2 + cr)) {
return false;
}
if (circleDistanceX <= rw/2) {
return true;
}
if (circleDistanceY <= rh/2) {
return true;
}
float cornerDistance = pow(circleDistanceX - rw/2, 2) +
pow(circleDistanceY - rh/2, 2);
if (cornerDistance <=pow(cr, 2)) {
return true;
} else {
return false;
}
}