Advertisement
cookertron

Pygame Distance Collision Example

Dec 30th, 2019
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. import pygame
  2. import math
  3.  
  4. # example of collision based on distance
  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. x = 320
  15. y = 240
  16. dead = False
  17.  
  18. # press ESCAPE to exit
  19. while True:
  20.     e = pygame.event.get()
  21.     if pygame.key.get_pressed()[pygame.K_ESCAPE]: break
  22.  
  23.     mx, my = pygame.mouse.get_pos()
  24.    
  25.     # calculate the distance between the centre of the surface and mouse location
  26.     # if the distance is less than the combine radius (60) of the two circles then
  27.     # a collision has occured.
  28.     if math.sqrt((mx - x) ** 2 + (my - y) ** 2) < 60:
  29.         dead = True
  30.  
  31.     surface.fill(black)
  32.     if not dead: pygame.draw.circle(surface, red, (x, y), 30)
  33.     pygame.draw.circle(surface, blue, (mx, my), 30)
  34.  
  35.     pygame.display.update()
  36.     pygame.time.Clock().tick(60)
  37.  
  38. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement