How do I detect if a rect is touching the edge in pygame?

Viewed 232

I am trying to write a space invaders style game where the idea is to pop the balloons. When it touches the edge it just moves back and forth between about a half a decimeter (1.5 inches). What I tried to do is an if elif statement to find if it is within the screen.

while run == True:
    clock.tick(60)
    for event in py.event.get():
        if event.type == py.QUIT:
            py.quit()
            quit()
    keys = py.key.get_pressed()
    charrect.x += (keys[py.K_RIGHT] - keys[py.K_LEFT]) * 4
    charrect.clamp_ip(screen.get_rect())
    if keys[py.K_SPACE]:
        while charrect.y != 0:
            clock.tick(60)
            charrect.y -= 2
            brect.x += bloonspeed
            brect.clamp_ip(screen.get_rect())
            screen.fill(white)
            screen.blit(character, charrect)
            screen.blit(bloon, brect)
            py.display.update()
    if brect.x == 70:
        bloonspeed = -4
    elif brect.x == 0:
        bloonspeed = 4
    brect.x += bloonspeed
    
    screen.fill(white)
    screen.blit(bloon, brect)
    screen.blit(character, charrect)
    py.display.update()

Is there a way to use clamp or clamp_ip in an if statement to detect their collision?

1 Answers

Is there a way to use clamp or clamp_ip in an if statement to detect their collision?

Use pygame.Rect.contains to test if one rectangle is inside another:

contains(Rect) -> bool

Returns true when the argument is completely inside the Rect.

e.g.:

if not screen.get_rect().contains(brect):
    # do something
Related