0
votes

I have to submit a Breakout clone and I'm struggling with the collision detection of the ball and the bricks. Basically, the collision detection works, but the ball destroys the brick about 10 pixels away from the visual object. I'm checking the bounds of both objects, but I guess the problem is that the ball is a moving object and the brick is a static one.

for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        brick = brickArray[i][j];
        if (brick == null)
            continue;
            areBricksLeft = true;
            Bounds brickBounds = brick.getBoundsInParent();
            Bounds ballBounds = ball.getBoundsInParent();

        if (brickBounds.intersects(ballBounds) ) {
            brick.removeBrickAt(i, j, brick, brickArray, brickPane);
            didHitBrick = true;
        }
    }
}
1
I think it's because of the round shape of the ball, The x position of the circle starts from the center while a rectangle or square have the x position at the beginning.Bo Halim

1 Answers

0
votes

Thanks for the hint I found the mistake. I replaced my condition with this:

double ballX = ball.getLayoutX() + ball.getRadius();
double ballY = ball.getLayoutY() + ball.getRadius();

if ((ballX <= brickBounds.getMaxX() - 10 && ballX >= brickBounds.getMinX() -10) && 
   (ballY <= brickBounds.getMaxY() - 10  && ballY >= brickBounds.getMinY() - 10)) {
    brick.removeBrickAt(i, j, brick, brickArray, brickPane);
    didHitBrick = true;
}

Now it is possible to adjust the collision by substracting and adding values to the bounds.