Search code examples
javacollisiondetectionbouncebreakout

Rectangle and Circle Collision Java using .intersection


I am making a breakout game for a school project. The only problem I am running into is the Ball Bouncing when the Ball and Bricks collide. I used ball1.getEllipse().intersects(b.getRectangle()) allowing me to figure out when it is colliding and delete the brick. The bouncing chances depending on the side it collided with. This is the main problem. The .intersect piece does not show me which side the brick gets hit by. I need this to know whether to change the x or y speed. If anyone has any idea on how to figure this out, please leave your input (I have been trying to think of a solution for 5 hours, I gave up)

 public void collision(int i) {

    for (Block b : blocks) {
        if (ball1.getEllipse().intersects(b.getRectangle())) {
            if (!b.isDestroyed()) {
                b.destroy();
                blockCount-=1;
                ball1.brickBounce();`public void collision(int i) {

Solution

  • From what I understand from your question, you want to know which side of the rectangle the ball is hitting. A simple way of doing this would be to take the position of the ball and the position of the rectangle and compare the two. If the ball's x position is less than the rectangles x position - half its width(to get the x position of the bound), then the ball hit on the left side. You can then do the opposite for the right side. Checking if it hit on top or bottom is similar just with the y positions and the rectangle's height. Do note that I'm assuming the x and y position of each shape is the center, if not only minor adjustments should have to be made to get the same result as if it were the center.