Pygame collision check bug

Question:

I recently started making Atari Breakout in Pygame and I encountered a weird bug. Whenever the ball touches the left side of the paddle, it bounces off normally but when it’s on the right, it flies through the paddle. Please help, because I don’t know how to fix it.

This is my code:

import pygame, random, math

pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Atari Breakout')

player = pygame.image.load('player copy.png')
ball = pygame.image.load('poland.png')

ballx, bally = 400, 300
balldx, balldy = 2,2
def isCollision(x1,y1,x2,y2):
    distance = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
    if distance <= 32:
        return True
    else:
        return False
running = True

while running:

    screen.fill((0,0,0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pos = pygame.mouse.get_pos()
    if isCollision(ballx, bally, pos[0], 525):
        balldy *= -1
    if bally >= 0:
        balldy *= -1
    if bally <= 570:
        balldy *= -1
    if ballx <= 0:
        balldx *= -1
    if ballx >= 770:
        balldx *= -1

    ballx += balldx
    bally += balldy

    screen.blit(player, (pos[0], 525))
    screen.blit(ball, (ballx,bally))

    pygame.display.update()
Asked By: Stqrosta

||

Answers:

Actually isCollision computes the Euclidean distance between the top left of the rectangle which surrounds the ball and the top left of the paddle.
The shape of the player (paddle) is a rectangle with a very long and a very short side. Thus the collision algorithm doesn’t work at all. I recommend to use pygame.Rect objects and colliderect, to detect a collision between the ball and the player. e.g.:

def isCollision(x1,y1,x2,y2):
    ballRect = ball.get_rect(topleft = (x1, y1))
    playerRect = player.get_rect(topleft = (x2, y2))
    return ballRect.colliderect(playerRect)
while running:
    # [...]

    pos = pygame.mouse.get_pos()
    if isCollision(ballx, bally, pos[0], 525):
        balldy *= -1
Answered By: Rabbid76