其他分享
首页 > 其他分享> > 如何在Pygame中检测对象之间的碰撞?

如何在Pygame中检测对象之间的碰撞?

作者:互联网

我正在Pygame中制作侧滚动游戏,如果狐狸精灵与树碰撞,则应该打印“ COLLIDE”.但这是行不通的.如何解决此问题以检测狐狸和树之间的碰撞?这是代码:

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

xtree是树的x坐标,treewidth是树的宽度,foxsprite1是fox.

解决方法:

保持对象位置和大小为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)

然后你可以使用

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

Rect()非常有用.你可以用它来咬

screen.blit(fox_image, fox_rect)

您可以使用它在屏幕上居中放置对象

screen_rect = screen.get_rect()

fox_rect.center = screen_rect.center

或将对象保留在屏幕上(并且不能离开屏幕)

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

或更简单

fox_rect.clamp_ip(screen_rect)

参见:Program Arcade Games With Python And PygameExample code and programs

标签:collision,python,pygame,collision-detection
来源: https://codeday.me/bug/20191013/1911208.html