在蒙版图像上检测鼠标事件 pygame

Detect mouse event on masked image pygame

我创建了一个点击器游戏并且我有一个透明图像(我在 Mask 中为 Pixel Perfect Collision 设置)但是当我也点击透明部分时,检测到 MOUSEBUTTONDOWN 事件。


实际上,我在播放器中的代码 Class 是:

self.image = pygame.image.load(str(level) + ".png").convert_alpha()
self.mask = pygame.mask.from_surface(self.image)
self.image_rect = self.image.get_rect(center=(WW, HH))

还有这个,在主循环中:

x, y = event.pos
if my_player.image_rect.collidepoint(x, y):
    my_player.click()

所以我希望只有当我点击图像的彩色部分而不是透明背景时才触发点击事件。

谢谢,

除了 my_player.image_rect.collidepoint(x, y),还要检查 Mask.get_at:

get_at()

Returns nonzero if the bit at (x,y) is set.
get_at((x,y)) -> int

请注意,您必须将全局鼠标位置转换为蒙版上的位置。


这是一个可运行的例子:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
class Cat:
    def __init__(self):
        self.image = pygame.image.load('cat.png').convert_alpha()
        self.image = pygame.transform.scale(self.image, (300, 200))
        self.rect = self.image.get_rect(center=(400, 300))
        self.mask = pygame.mask.from_surface(self.image)
running = True
cat = Cat()
while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False

    pos = pygame.mouse.get_pos()
    pos_in_mask = pos[0] - cat.rect.x, pos[1] - cat.rect.y
    touching = cat.rect.collidepoint(*pos) and cat.mask.get_at(pos_in_mask)

    screen.fill(pygame.Color('red') if touching else pygame.Color('green'))
    screen.blit(cat.image, cat.rect)
    pygame.display.update()


此外,self.image_rect 按照惯例应命名为 self.rect。这不是绝对必要的;但这仍然是一个好主意,使您能够使用 pygame 的 Sprite class(示例中未显示)。