### Java Collision Detection and bounce - Circle and rectangle

Collision detection between circle(any object) and rectangular wall is simple.
For collision detection we simply compare the distances. And if collision between ball and wall is detected, we change the directions of their speeds for bouncing the ball.

Here is the code:
The Circle
``````    float x, y; // Ball's center x and y
float speedX, speedY; // Ball's speed per step in x and y
``````

Collision detect and bounce
``````    public static void collisionWithWall(Rectangle wall, Ball ball) {
float ballMinX = wall.x + ball.radius;
float ballMinY = wall.y + ball.radius;
float ballMaxX = wall.width - ball.radius;
float ballMaxY = wall.height - ball.radius;
if (ball.x < ballMinX) {
ball.speedX = -ball.speedX; // Reflect along normal
ball.x = ballMinX; // Re-position the ball at the edge
} else if (ball.x > ballMaxX) {
ball.speedX = -ball.speedX;
ball.x = ballMaxX;
}
// May cross both x and y bounds
if (ball.y < ballMinY) {
ball.speedY = -ball.speedY;
ball.y = ballMinY;
} else if (ball.y > ballMaxY) {
ball.speedY = -ball.speedY;
ball.y = ballMaxY;
}
}
``````

1. 2. 