Skip to content Skip to sidebar Skip to footer

How To Detect Collision Between Objects In Pygame?

I'm making a sidescrolling game in Pygame, and if the fox sprite collides with the tree, it is supposed to print 'COLLIDE'. But it doesn't work. How can I fix this to detect collis

Solution 1:

Keep object position and size as pygame.Rect()

fox_rect = pygame.Rect(fox_x, fox_y, fox_width, fox_height)
tree_rect = pygame.Rect(tree_x, tree_y, tree_width, tree_height)

and then you can use

if fox_rect.colliderect(tree_rect): 
     print("COLLIDE")

Rect() is very usefull. You can use it to blit

screen.blit(fox_image, fox_rect)

You can use it to center object on screen

screen_rect = screen.get_rect()

fox_rect.center = screen_rect.center

or to keep object on the screen (and it can't leave screen)

if fox_rect.right > screen_rect.right:
    fox_rect.right = screen_rect.right

if fox_rect.left < screen_rect.left:
    fox_rect.left = screen_rect.left

or simpler

fox_rect.clamp_ip(screen_rect)

see: Program Arcade Games With Python And Pygame and Example code and programs

Post a Comment for "How To Detect Collision Between Objects In Pygame?"