Advertisement
cookertron

Pygame Rectangle Collision Example

Dec 30th, 2019
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. import pygame
  2. import math
  3.  
  4. # example of rectangle collision
  5. # fb.com/groups/pygame
  6.  
  7. pygame.init()
  8. surface = pygame.display.set_mode((640, 480))
  9.  
  10. black = [0, 0, 0]
  11. red = [255, 0, 0]
  12. blue = [0, 0, 255]
  13.  
  14. size = 60
  15. x = 290
  16. y = 180
  17. dead = False
  18.  
  19. # press ESCAPE to exit
  20. while True:
  21.     e = pygame.event.get()
  22.     if pygame.key.get_pressed()[pygame.K_ESCAPE]: break
  23.  
  24.     mx, my = pygame.mouse.get_pos()
  25.    
  26.     # work out if the rectangles overlap
  27.     if not (mx > x + size or mx + size < x or my > y + size or my + size < y):
  28.         dead = True
  29.  
  30.     surface.fill(black)
  31.     if not dead: pygame.draw.rect(surface, red, (x, y, size, size))
  32.     pygame.draw.rect(surface, blue, (mx, my, size, size))
  33.  
  34.     pygame.display.update()
  35.     pygame.time.Clock().tick(60)
  36.  
  37. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement