可视化的mask碰撞检测原理示例程序

"""
   mask碰撞检测原理示例程序。mask是由010101...组成的。1代表相应的像素点不透明。0代表相应坐标的像素点是透明,即那里是空的。
"""
import pygame

pygame.init()
screen = pygame.display.set_mode((480,360))

width,height = 50,50
x1,y1 = 100,100
sur1 = pygame.Surface((width,height)).convert_alpha()
sur1.fill((255,100,100,0))                # 最后的0代表完全透明
sur1_rect = sur1.get_rect(topleft=(x1,y1))  # 定位
sur1_mask = pygame.mask.from_surface(sur1)  # 取掩膜
print(sur1_mask.get_at((1,1)))              # 取(1,1)掩膜值
screen.blit(sur1,sur1_rect)

x2,y2 = 120,128
sur2 = pygame.Surface((width,height)).convert_alpha()
sur2.fill((100,100,255))
sur2_rect = sur2.get_rect(topleft=(x2,y2)) # 定位
sur2_mask = pygame.mask.from_surface(sur2)  # 取掩膜
screen.blit(sur2,sur2_rect)                 # 贴到屏幕
pygame.display.update()

offset = x2 - x1 , y2 - y1

p = sur1_mask.overlap(sur2_mask,offset)
print(p)


You must log in to read the rest of this article. Please log in or register as a user.