如何使用两张图片的像素完美碰撞pygame

How to use pixel perfect collision with two images pygame

注意:我不想使用pygame精灵。

我正在制作一个简单的游戏,我需要一种方法来检测两个图像是否在 pygame 中使用像素完美碰撞重叠。到目前为止我找到的所有答案都要求我使用 pygame 精灵,我不喜欢使用它,因为我对对象的控制较少。

(这些图片有透明背景)

首先,不要害怕精灵。

A Sprite 只是一个带有图像的简单 class(存储在 image 属性中的 Surface)以及图像的大小和位置(一个Rect存储在rect属性中)。

所以当你像这样使用 class 时:

class Player:
    def __init__(self, image, pos):
        self.image = image
        self.pos = pos

    def draw(self, screen):
        screen.blit(self.image, self.pos)

您可以简单地使用 Sprite class 代替,因为变化不大:

class Player(pygame.sprite.Sprite):
    def __init__(self, image, pos):
        super().__init__()
        self.image = image
        self.rect = image.get_rect(center=pos)

相反,它变得更简单,因为我们可以让 pygame 处理将图像 blit 到屏幕。

因此,要使用像素完美碰撞,您可以使用 pygame 的 Mask class. Use pygame.mask.from_surface to create a Mask from your Surface, and use pygame.mask.Mask.overlap 来检查两个蒙版是否重叠。

使用 Sprite class 更容易使用,因为您可以只使用像 spritecollide together with collide_mask 这样的函数。

但如果您不想使用 Sprite class,只需查看 collide_maskimplemented 的区别,即可了解如何使用遮罩:

def collide_mask(left, right):
    xoffset = right.rect[0] - left.rect[0]
    yoffset = right.rect[1] - left.rect[1]
    try:
        leftmask = left.mask
    except AttributeError:
        leftmask = from_surface(left.image)
    try:
        rightmask = right.mask
    except AttributeError:
        rightmask = from_surface(right.image)
    return leftmask.overlap(rightmask, (xoffset, yoffset))