【问题标题】:Pygame Collision ExplainedPygame 碰撞解释
【发布时间】:2026-01-31 00:40:01
【问题描述】:

我是 Python/Pygame 的新手。我已经能够在小型测试程序中拼凑一些东西,但试图掌握碰撞只是没有发生。我已经尝试过多个教程,但我觉得我需要将它完全分解,然后才能很好地理解它。

有人能解释一下像 colliderect(Rect) 这样的东西是如何工作的吗? 我需要一个碰撞函数的类还是我可以只取两个矩形并得到一个结果?

我正在尝试使用的代码如下。我能够制作两个图像,每个图像都被一个矩形包围,我假设碰撞仅适用于精灵而不适用于图像?我可以用鼠标控制其中一张图片,当我将鼠标悬停并点击静态图片时,我希望触发碰撞检测。

任何帮助将不胜感激。

谢谢

~T

pygame.init()
clock = pygame.time.Clock()

size=width, height= 600,400
screen = pygame.display.set_mode(size)

rageface = pygame.image.load("rageface.jpg")
rageface = pygame.transform.scale(rageface,(100,100))
rageface2 = pygame.transform.scale(rageface,(100,100))

black = (100,0,0)
green = (0,150,150)
r=0
x=50
y=50
mx,my = pygame.mouse.get_pos()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:
            mx,my = pygame.mouse.get_pos()

    #colliderect(Rect) ????????????????????

    screen.fill((r,0,0))

    pygame.draw.rect(screen, black, [50, 50, 250, 100], 0)
    pygame.draw.rect(screen, green, [mx-50, my-50, 250, 100], 0)
    screen.blit(rageface2,(mx-50,my-50))
    screen.blit(rageface,(x,y))


    clock.tick(60)

    pygame.display.flip()

【问题讨论】:

    标签: python-3.x pygame collision-detection collision


    【解决方案1】:

    colliderect 是这样工作的:

    rect1.colliderect(rect2)
    

    如果两个矩形发生碰撞,这将返回True,否则返回False

    这里是documentation

    colliderect是pygameRect类的方法,精灵也有碰撞方法

    在 pygame 中,加载的图像是一个表面,就像 pygame 屏幕/显示器一样,​​从您使用的表面获取一个矩形:

    Surface.get_rect()
    

    所以要得到一个说rageface 只需做rage_rect = rageface.get_rect() 现在你可以像使用矩形一样使用rage_rect

    告诉我这是否清楚或者您需要更多帮助!

    【讨论】:

    • 非常酷!谢谢你。这正是我所需要的。 :) 我让它工作。出于某种原因,当我使用surface.get_rect 时,colliderect 在我实际将图像相互移动之前返回true。无论如何,我会继续搞砸它,看看我能做些什么。再次感谢!
    • 是的,没问题,Pygame 一开始可能会有点令人困惑,但是一旦你掌握了它的窍门,它真的很有趣!祝你好运!