Check collision between a image and a line

一笑奈何 提交于 2021-02-05 08:18:15

问题


I check collision:

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

Its working between two images.

But if I want to check collision between a image and pygame.draw.line(...) (I use it for create mask from line). mask.overlap returns 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)

Sorry for my english.


回答1:


You missed to create a surface with per pixel alpha by .convert_alpha(), before creating the mask from the "line" Surface:

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)

See the example: repl.it/@Rabbid76/PyGame-PyGame-SurfaceLineMaskIntersect-1



来源:https://stackoverflow.com/questions/58662215/check-collision-between-a-image-and-a-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!