如何可视化 pygame 中 2 个掩码的重叠区域?

How can I visualize the overlapping area of 2 masks in pygame?

当我在 Pygame 中创建遮罩时,例如:

self.mask = pygame.mask.from_surface(self.image) 

我能看到结果吗,布尔值网格?

还有问题2,当两个遮罩重叠时,我可以让重叠部分可见吗?

Can i see the result, the grid with Boolean values.

您只能在屏幕上看到您正在绘制的内容。无法在屏幕上绘制遮罩,因此您看不到它。

Can I make an overlap visible when two mask overlap?

创建一个 Mask 包含 2 Maskspygame.mask.Mask.overlap_mask.
之间的重叠设置位 使用 pygame.mask.Mask.to_surfaceMask 转换为 Surface。例如:

overlap_mask = mask1.overlap_mask(mask2, (offset_x, offset_y))
overlap_surf = overlap_mask.to_surface(setcolor= (255, 0, 0))
overlap_surf.set_colorkey((0, 0, 0))

最小示例:

重叠的像素为红色。

import pygame, math

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

image1 = pygame.image.load("Banana.png")
image2 = pygame.image.load("Bird.png")
rect1 = image1.get_rect(center = (165, 150))
rect2 = image1.get_rect(center = (135, 150))
mask1 = pygame.mask.from_surface(image1)
mask2 = pygame.mask.from_surface(image2)

angle = 0
run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    angle += 0.01
    rect1.centery = 150 + round(60 * math.sin(angle))        

    offset_x = rect2.x - rect1.x
    offset_y = rect2.y - rect1.y
    overlap_mask = mask1.overlap_mask(mask2, (offset_x, offset_y))
    overlap_surf = overlap_mask.to_surface(setcolor = (255, 0, 0))
    overlap_surf.set_colorkey((0, 0, 0))

    window.fill(0)
    window.blit(image1, rect1)
    window.blit(image2, rect2)
    window.blit(overlap_surf, rect1)
    pygame.display.flip()

pygame.quit()
exit()