1

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.


 
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
maria
  • 42
  • 5
  • The problem is that you check collision every frame, so it doesn't just collide once. It collides every frame that the rectangles overlap. Should one of the rectangles be deleted by the collision? Should the player be invincible for a couple seconds after getting hit? Without knowing your game, I can't give "a solution," but I can at least point out the problem for you. – Starbuck5 Aug 03 '21 at 22:57

1 Answers1

0

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 

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174