python - 如何在 pygame 中可视化 2 个蒙版的重叠区域?

标签 python pygame

例如,当我在 Pygame 中创建掩码时:

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

我可以看到结果,带有 bool 值的网格吗?

问题 2,当两个蒙版重叠时,我可以使重叠可见吗?

最佳答案

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

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

Can I make an overlap visible when two mask overlap?

创建一个掩码,其中包含2个掩码之间的重叠设置位,pygame.mask.Mask.overlap_mask .
使用 pygame.mask.Mask.to_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()

关于python - 如何在 pygame 中可视化 2 个蒙版的重叠区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70485132/

相关文章:

python - Pygame 不会播放音频,但只有在作为守护进程运行时才会播放

python - 如何使用 pyopengl 和 pygame 在 python 中制作球体?

python - 如何检查哪个更大 : a**b or b**a for big numbers?

python - struct.pack() 因 int > 127 失败

python - 有没有办法在 Python 中获取对象的当前引用计数?

Python C 模块函数参数引用计数

python - 如何在通过检查第一个 pygame.MOUSEBUTTONDOWN 开始的循环内检测第二个 pygame.MOUSEBUTTONDOWN

python - Pygame 显示仅在我退出时更新

python - selenium.common.exceptions.WebDriverException : Message: Service chromedriver unexpectedly exited. 状态代码为:1

python - pygame 不在 Python 3.6.4 中导入