How do I find collisions between characters and images within PyGame? I have drawn a player from an image, and have drawn the walls from tiles, so how would I detect these collisions?
If you use the pygame Rect class to represent the boundaries of your object, you can detect whether two are colliding by using the Rect.colliderect function. For example:
import pygame
a = pygame.Rect((1, 1), (2, 2))
b = pygame.Rect((0, 0), (2, 2))
c = pygame.Rect((0, 0), (1, 1))
a.colliderect(b)
# 1
a.colliderect(c)
# 0
b.colliderect(c)
# 1
a is colliding with b, and b is colliding with c, but a is not colliding with c. Note that rects that share a boundary are not colliding.
Pygame also supports letting you use a Rect as the position for an image when you want to 'blit' it onto the screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With