problem when rectangles collide in pygame

Question:

I’m trying to make a simple game but I’m stuck because when the two rectangles collide the lives are supposed to go down one by one, I’m pretty sure it’s because of the pixels but I still don’t know how to fix it. Am I supposed to change the collision method?

player_img = pygame.image.load('umbrella.png')
p_img = pygame.transform.scale(player_img, (128, 128))
px = 330
py = 430
px_change = 0
r1 = p_img.get_rect()


raio_img = pygame.image.load('untitleddesign_1_original-192.png')
r_img = pygame.transform.scale(raio_img, (40, 60))
rx = 335
ry = 50
r_direcao = 3
r_counter = 0
raio_velocidade = 6
r2 = r_img.get_rect()


def raio(x, y):
    game_screen.blit(r_img, (r2))


def player(x, y):
    x = 330
    y = 430
    game_screen.blit(p_img, (r1.x, r1.y))


life = 0 
f = pygame.font.Font('dogica.ttf', 16)
fx = 5
fy = 5

def font(x, y):
    s = f.render("life : " + str(life), True, (0, 0, 0))
    game_screen.blit(s, (x, y))
     

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run = False

    colision = r2.colliderect(r1) 
    if colision:
        life -= 1  # here when i collide the two rects the life goes down by 31 instead of going by one.


 
Asked By: maria

||

Answers:

The collision is recognized as long as the rectangles collide. Therefore, the ‘life’ is decremented in successive frames as long as the rectangles collide.

Add a variable that indicates whether the rectangles collided in the previous frame. Don’t decrease the ‘life’ when the rectangles collided:

collided_in_previous_frame = False

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

    # [...]

    colision = r2.colliderect(r1) 
    if colision and not collided_in_previous_frame:
        life -= 1
    collided_in_previous_frame = colision 

    # [...]
Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.