Skip to content Skip to sidebar Skip to footer

How To Make The Ball Bounce Only If It Hits The Paddle In Python, Pygame (breakout Recreation)

can anyone help me with this? i am having trouble making a simple way to detect if a ball hits a paddle and then bounce it by changing the rect_change_y variable. here is code that

Solution 1:

You can use the Rect class to represent the ball and the paddle, and also take advantage of the methods this class provides:

  • Rect.move_ip to move the rectangles in place:

    myrect = pygame.Rect(0, 0, 10, 10)
    myrect.move_ip(100, 50)
    

    myrect top left corner is at (100, 50) and keeps the same width and height.

  • Rect.clamp_ip to ensure the rectangles are both inside the screen.

    myrect = pygame.Rect(100, 0, 10, 10)
    bounds = pygame.Rect(0, 0, 50, 50)
    myrect.clamp_ip(bounds)
    

    myrect top left corner is at (40, 0) and its bottom right corner at (10, 50), inside bounds rectangle.

  • Rect.colliderect to check if the ball and the paddle collide.

    myrect = pygame.Rect(0, 0, 10, 10)
    another = pygame.Rect(5, 5, 10, 10)
    print(myrect.colliderect(another)) # 1

    Since myrect and another overlap, when you call colliderect it returns 1, indicating that there is a collision between the two rectangles.


I really like Pygame, so I don't mind to rewrite your program applying these suggestions. Hope it helps:

import pygame

# Constants
WIDTH = 700
HEIGHT = 500
SCREEN_AREA = pygame.Rect(0, 0, WIDTH, HEIGHT)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# Initialization
pygame.init()
screen = pygame.display.set_mode([WIDTH, HEIGHT])
pygame.mouse.set_visible(0)
pygame.display.set_caption("Breakout Recreation WIP")
clock = pygame.time.Clock()

# Variables
paddle = pygame.Rect(350, 480, 50, 10)
ball = pygame.Rect(10, 250, 15, 15)
paddle_movement_x = 0
ball_direction = (1, 1)
balls = 3
done = False

while not done and balls > 0:

    # Process events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle_movement_x = -2
        elif keys[pygame.K_RIGHT]:
            paddle_movement_x = 2
        else:
            paddle_movement_x = 0

    # Move paddle
    paddle.move_ip(paddle_movement_x, 0)
    paddle.clamp_ip(SCREEN_AREA)

    # Move ball
    ball.move_ip(*ball_direction)
    if ball.right > WIDTH or ball.left < 0:
        ball_direction = -ball_direction[0], ball_direction[1]
    elif ball.top < 0 or ball.bottom > HEIGHT or paddle.colliderect(ball):
        ball_direction = ball_direction[0], -ball_direction[1]
    ball.clamp_ip(SCREEN_AREA)

    # Redraw screen
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, paddle)
    pygame.draw.rect(screen, WHITE, ball)
    pygame.display.flip()
    clock.tick(100)

pygame.quit()

Post a Comment for "How To Make The Ball Bounce Only If It Hits The Paddle In Python, Pygame (breakout Recreation)"