首页 > 解决方案 > 检查图像和线条之间的碰撞

问题描述

我检查碰撞:

offset = (x0 - x1, y0 - y1)
result = player1.mask.overlap(player2, offset)

它在两个图像之间工作。

但是,如果我想检查图像和pygame.draw.line(...)(我用来从线创建蒙版)之间的冲突。mask.overlap返回None

surface = self.gameDisplay.subsurface(pygame.draw.line(self.gameDisplay, colors.GREEN, [100, 100], [200, 200], 5))
line_mask = pygame.mask.from_surface(surface)
pygame.draw.line(self.gameDisplay, colors.GREEN, [100, 100], [200, 200], 5)

offset = (x0 - x1, y0 - y1)
result = player1.mask.overlap(mask, offset)

对不起我的英语不好。

标签: pythonpygame

解决方案


.convert_alpha()在从“线”表面创建蒙版之前,您错过了创建每个像素 alpha 的表面:

line_rect = pygame.draw.line(gameDisplay, colors.GREEN, [100, 100], [200, 200], 5)
line_surf = gameDisplay.subsurface(line_rect)
line_mask = pygame.mask.from_surface(line_surf.convert_alpha())

x0, y0 = line_rect.topleft
x1, y1 = player1.rect.topleft

offset = (x0 - x1, y0 - y1)
if player1.mask.overlap(line_mask, offset):
    print("hit : ", count)

请参阅示例: repl.it/@Rabbid76/PyGame-PyGame-SurfaceLineMaskIntersect-1


推荐阅读