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

标签 python pygame collision-detection collision

我正在 Pygame 中制作一个横向卷轴游戏,如果狐狸 Sprite 与树碰撞,它应该打印“COLLIDE”。但这不起作用。我该如何解决这个问题以检测狐狸和树之间的碰撞?代码如下:

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

xtree是树的x坐标,treewidth是树的宽度,foxsprite1是狐狸。

最佳答案

将对象位置和大小保持为 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() 非常有用。你可以用它来 blit

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

关于python - 如何检测 Pygame 中对象之间的碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001207/

相关文章:

python - 一次更新所有显示 PyGame

oop - OO 设计和镜像/复制方法

java - 碰撞事件

python - 子进程:PyDev 控制台与 cmd.exe

Python:为文件列表构造唯一的文件名

python - 如何在 cython 中访问枚举?

python - 如何使这个功能在django 的views.py 中工作?

python - 如何在pygame中制作具有透明背景的表面

python - pygame.image.load 不工作

java - Activity 重新启动后功能发生变化