Advertisement
cookertron

Python Pygame Center Camera

Jan 25th, 2021
1,094
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. import sys, time, random
  2. import pygame
  3.  
  4. class c:
  5.     def __init__(s, x, y, r):
  6.         s.rect = pygame.Rect(x - r // 2, y - r // 2, r * 2, r * 2)
  7.         s.rad = r
  8.  
  9.     def draw(s):
  10.         global PDS, VP
  11.  
  12.         if s.rect.colliderect(VP):
  13.             #print(s.rect.centerx)
  14.             pygame.draw.circle(PDS, (255, 255, 255), (s.rect.centerx - VP.x, s.rect.centery - VP.y), s.rad)
  15.  
  16. pygame.init()
  17.  
  18. PDR = pygame.Rect(0, 0, 1024, 720)
  19. PDCENTER = pygame.math.Vector2(PDR.center)
  20. PDS = pygame.display.set_mode(PDR.size)
  21. FPS = 120
  22.  
  23. # viewport or camera
  24. VP = pygame.Rect(0, 0, 1024, 720)
  25.  
  26. PLAYER_RADIUS = pygame.math.Vector2(20)
  27. PLAYER = pygame.Rect(PDCENTER - PLAYER_RADIUS, PLAYER_RADIUS * 2)
  28.  
  29. # generate NPCs
  30. circles = [c(random.randint(0, 10000), random.randint(0, 4000), random.randint(5, 20)) for i in range(100)]
  31.  
  32. while True:
  33.     events = pygame.event.get()
  34.     for e in events:
  35.         if e.type == pygame.QUIT: sys.exit()
  36.  
  37.     PDS.fill((0, 0, 0))
  38.  
  39.     # default player is green
  40.     playerColor = (0, 255, 0)
  41.     # draw NPC
  42.     for circle in circles:
  43.         circle.draw()
  44.         if circle.rect.colliderect((PLAYER.x + VP.x, PLAYER.y + VP.y), PLAYER_RADIUS * 2):
  45.             playerColor = (255, 0, 0) # player turns red if collides with NPC
  46.  
  47.     # draw player in red
  48.     pygame.draw.circle(PDS, playerColor, PLAYER.center, PLAYER_RADIUS[0])
  49.  
  50.     pygame.display.update()
  51.  
  52.     k = pygame.key.get_pressed()
  53.     if k[pygame.K_RIGHT]:
  54.         VP.move_ip(1, 0)
  55.     if k[pygame.K_LEFT]:
  56.         VP.move_ip(-1, 0)
  57.     if k[pygame.K_UP]:
  58.         VP.move_ip(0, -1)
  59.     if k[pygame.K_DOWN]:
  60.         VP.move_ip(0, 1)
  61.  
  62. pygame.quit()
  63. sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement