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

Cod*_*gFR 2 python events pygame mask

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


实际上,我在 Player 类中的代码是:

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))
Run Code Online (Sandbox Code Playgroud)

这在主循环中:

x, y = event.pos
if my_player.image_rect.collidepoint(x, y):
    my_player.click()
Run Code Online (Sandbox Code Playgroud)

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

谢谢,

slo*_*oth 6

此外my_player.image_rect.collidepoint(x, y),还要检查Mask.get_at

get_at()

如果 (x,y) 处的位被设置,则返回非零值。
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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


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