简体   繁体   中英

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 collision between the fox and the tree? Here's the code:

if foxsprite1 > xtree  and foxsprite1 < xtree + treewidth or foxsprite1 + treewidth > xtree and foxsprite1 + treewidth < xtree + treewidth:
        print ("COLLIDE")

xtree is the x coordinate of the tree, treewidth is the width of the tree, and foxsprite1 is the fox.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM