[英]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". 我正在Pygame中制作侧滚动游戏,如果狐狸精灵与树碰撞,则应该打印“ 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. xtree是树的x坐标,treewidth是树的宽度,foxsprite1是fox。
Keep object position and size as pygame.Rect() 保持对象的位置和大小为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. Rect()
非常有用。 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 请参阅: 使用Python和Pygame编程街机游戏以及示例代码和程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.