How to detect collision between objects in Pygame?

故事扮演 提交于 2019-12-20 04:15:21

问题


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.


回答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



来源:https://stackoverflow.com/questions/35001207/how-to-detect-collision-between-objects-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!