0
votes

I am working on a brick breaker game for Android. Currently, I am using an ArrayList for the bricks. I need to remove each one individually from the list and the screen upon collision with the ball. Currently, when the ball collides with the very last brick in the array (bottom right corner), half of the array gets removed (every other brick). Upon colliding with it again, it removes a few more bricks randomly, but none of this is even close to what I need.

Here is my code. brick is an object within the Bricks ArrayList.

for (int i = 0; i <= bricks.size(); i++) {
    if (RectF.intersects(brick.rect, ball.rect)) {
        bricks.remove(bricks.get(i));
        ball.dy = -ball.dy;
        score += 10;
    }
}
1
i <= bricks.size() in the for seems wrong. Use < instead of <=? - Pang
didn't affect anything - throwaway713281
yes i have done that. - throwaway713281
Calling bricks.remove() while iterating bricks in ascending order seems a bad idea. - Pang
Why use brick.rect instead of bricks.get(i).rect in your if line? Is the if line supposed to be not directly dependent on i? - Pang

1 Answers

0
votes

You have to use an Iterator:

for (Iterator<Brick> it = bricks.iterator(); it.hasNext();) {
    Brick brick = it.next();

    if (RectF.intersects(brick.rect, ball.rect)) {
        it.remove();
        ball.dy = -ball.dy;
        score += 10;
    }
}

Or you can just reverse original code to delete bricks from the end.