Advertisement
cookertron

Pygame Bit Mask Collision Example

Dec 30th, 2019
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. import pygame
  2. import math
  3.  
  4. # example of bit mask collision
  5. # fb.com/groups/pygame
  6.  
  7. pygame.init()
  8. surface = pygame.display.set_mode((640, 480))
  9.  
  10.  
  11. black = [0, 0, 0]
  12. red = [255, 0, 0]
  13. blue = [0, 0, 255]
  14.  
  15. # create two sprites
  16. surf1 = pygame.Surface((60, 60))
  17. pygame.draw.circle(surf1, red, (15, 15), 15, 0)
  18. pygame.draw.rect(surf1, red, (30, 30, 30, 30))
  19. surf2 = pygame.Surface((60, 60))
  20. pygame.draw.circle(surf2, blue, (45, 45), 15, 0)
  21. pygame.draw.rect(surf2, blue, (0, 0, 30, 30))
  22.  
  23. # make the black background of the sprites transparent
  24. surf1.set_colorkey(black)
  25. surf2.set_colorkey(black)
  26.  
  27. # get the sprites bit masks
  28. surf1_bitmask = pygame.mask.from_surface(surf1)
  29. surf2_bitmask = pygame.mask.from_surface(surf2)
  30.  
  31. x = 290
  32. y = 180
  33. dead = False
  34.  
  35. # press ESCAPE to exit
  36. while True:
  37.     e = pygame.event.get()
  38.     if pygame.key.get_pressed()[pygame.K_ESCAPE]: break
  39.  
  40.     mx, my = pygame.mouse.get_pos()
  41.    
  42.     # work out if the sprites bitmasks overlap
  43.     if surf1_bitmask.overlap(surf2_bitmask, (mx - x, my - y)):
  44.         dead = True
  45.  
  46.     surface.fill(black)
  47.     if not dead: surface.blit(surf1, (x, y))
  48.     surface.blit(surf2, (mx, my))
  49.  
  50.     pygame.display.update()
  51.     pygame.time.Clock().tick(60)
  52.  
  53. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement