如何在Pygame中检测对象之间的碰撞? [英] How to detect collision between objects in Pygame?

查看:83
本文介绍了如何在Pygame中检测对象之间的碰撞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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是xtree的x坐标

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

推荐答案

将对象的位置和大小保留为 pygame.Rect()

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)

,然后可以使用

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

Rect()非常有用。您可以使用它来屏蔽

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

或更简单

fox_rect.clamp_ip(screen_rect)

请参阅:使用Python和Pygame的程序街机游戏示例代码和程序

这篇关于如何在Pygame中检测对象之间的碰撞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆