π₯
Crash Detection
Right now, the bird flies straight through the pipes like a ghost. That is no fun. We need collision detection: the game needs to know when the bird hits something.
Invisible Boxes
To the computer, your bird and pipes are not pictures. They are rectangles. We call these hitboxes.
Rect = Rectangle
Pygame has a built-in tool called
pygame.Rect(x, y, width, height)
that creates an invisible rectangle. It comes with a method called
colliderect()
that checks if two rectangles are touching.
The Overlap Test
colliderect() returns
True if two rectangles overlap, False if they do not.
# Create hitboxes each framebird_rect = pygame.Rect(50, bird_y, 30, 30)pipe_top_rect = pygame.Rect(pipe_x, 0, 50, gap_y - 75)pipe_bottom_rect = pygame.Rect(pipe_x, gap_y + 75, 50, 600) # Check for collisionif bird_rect.colliderect(pipe_top_rect): game_active = False if bird_rect.colliderect(pipe_bottom_rect): game_active = False # Also check floor and ceilingif bird_y > 570 or bird_y < 0: game_active = FalseWhat Happens on Crash?
When we detect a collision, we set game_active = False.
Why use a variable instead of immediately quitting?
Your Turn: Detect the Crash
Use Pygameβs collision method to check if the bird hit a pipe.
Level Goal
Use colliderect to detect if the bird hits a pipe and end the game.