How to detect collision between objects in Pygame?

别说谁变了你拦得住时间么 提交于 2019-12-02 06:40:57

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

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