Every time the game view is updated, the ball moves a certain number of pixels. The directions for the ball are fairly limited, since only the horizontal velocity changes according to the plate position that the ball hits. The further the ball hits from the center of the plate, the faster the ball leaves in the X direction. The Y velocity stays the same throughout the level and gets faster in proportion to the level number.
The following figure shows on the left the ball movement speed based on the plate hit position and the level number, and on the right the ball direction based on the plate hit position.
Figure: Ball movement speed and direction
The checkPlateCollision method is used to detect a collision with the plate and to determine the X velocity of the ball when it bounces from the plate:
public void checkPlateCollision() { if (ball.collidesWith(plate, false)) { if (ball.getRefPixelY() < plate.getRefPixelY()) { ball.bounceUp(); // Calculate horizontal velocity relative to the distance // between plate center and collision point ball.setVelocityX((int) Math.ceil(r.scale(-8.0) * (plate.getRefPixelX() - ball.getRefPixelX()) / (plate.getPlateWidth()))); listener.handleEvent(EVENT_PLATE_COLLISION); // Inform listener } } }
In addition to the plate, the ball bounces off from the walls and bricks. Collision detection must be implemented using the built-in functionality of the Sprites . By default, the detection is based on the frame size. The bouncing functionality itself is nothing more than reflecting ball velocities.
Note that since most of the sprites in the game are glowing, it looks strange if the ball bounces immediately when the edge of the glow collides with something. To prevent premature bouncing, you can define a separate collision rectangle, so that, for example, the ball has a smaller square inside the sprite, and the smaller square is used to detect the collision and bounce the ball.
The following figure shows a separate collision rectangle for a ball on the left and the bounce (reflected ball velocity) on the right.
Figure: Bouncing the ball