0

I'm building a Breakout Ball game like Arkanoid, and I have a big problem when ball collide with bricks. It happens when ball collide on the corner of brick (brickX,brickX) (brickX,brickX+brickLength) (brickY,brickY) (brickX+brickLength, brickY).

This is my code:

private void checkCollision() {
        for(Brick brick : l.getCurrentLevel().getAllBricks()) {
            double bx = b.getX();
            if(brick.isShot())
                continue;
            if(b.getBounds().intersects(brick.getBounds())) {
                if (
                    (b.getX() == brick.getX() || b.getX() == brick.getX() + brick.getLength())
                    && (b.getY() >= brick.getY()  && b.getY() <= brick.getY() + brick.getHeight())
                )
                    b.setDx(-b.getDx());


                else
                    b.setDy(-b.getDy());
                if(brick.isDestroyable()) {
                    brick.shot();
                    b.setVelocity(b.getVelocity()+0.05);
                }

                break;
            }
        }
    }
Hsrtick
  • 9
  • 4

1 Answers1

0

At first glance, it looks like your problem is here:

(b.getX() == brick.getX() || b.getX() == brick.getX() + brick.getLength())

If x is incrementing by (for example) 5 every tick, then you can jump from b.getX() < brick.getX() to b.getX() > brick.getX() without ever hitting the equals condition. So when the ball enters the brick it fails that condition and jumps down to this one:

else
    b.setDy(-b.getDy());

So it reverses vertical direction when you wanted it to reverse horizontally (and maybe vertically too).

As a side note, you may want to get in the habit of using {} braces on your single-line if-statements, even though they're not strictly necessary. They will help your code look cleaner and avoid introducing bugs when things are modified later on.

Miltios
  • 249
  • 1
  • 6