cookertron

Pull and release ball

Mar 10th, 2022 (edited)
583
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. from random import randint, uniform
  2. import time
  3. import pygame
  4. from pygame import Rect as R
  5. from pygame import Vector2 as V
  6. from pygame.locals import *
  7.  
  8. WHITE = (255, 255, 255)
  9. RED = (255, 0, 0)
  10.  
  11. pygame.init()
  12. PDS = pygame.display.set_mode()
  13. PDR = PDS.get_rect()
  14. FPS = 120
  15.  
  16. ball = V(PDR.center)
  17. rad = 80
  18. v = V()
  19. f = V()
  20.  
  21. pressed = False
  22.  
  23. dts = time.time()
  24. while True:
  25.     pygame.event.get()
  26.    
  27.     now = time.time()
  28.     dt = (now - dts) * FPS
  29.     dts = now
  30.    
  31.     mp = V(pygame.mouse.get_pos())
  32.     dist = mp.distance_to(ball)
  33.    
  34.     mb = pygame.mouse.get_pressed()
  35.     if mb[0] and not pressed:
  36.         if dist <= rad:
  37.             pressed = True
  38.     if pressed:
  39.         if not mb[0] and dist > rad:
  40.             deg = V().angle_to(mp - ball)
  41.             a = V(1, 0)
  42.             b = a.rotate(deg + 180) * (dist - rad)
  43.             v = b / 10
  44.            
  45.             pressed = False
  46.    
  47.     ball += v * dt
  48.     if v.x != 0 or v.y != 0:
  49.         a = v.normalize()
  50.         v -= (a / 10) * dt
  51.     if ball.x + rad > PDR.w:
  52.         ball.x = PDR.w - rad
  53.         v.x = -v.x
  54.     if ball.x - rad < 0:
  55.         ball.x = rad
  56.         v.x = -v.x
  57.     if ball.y + rad > PDR.h:
  58.         ball.y = PDR.h - rad
  59.         v.y = -v.y
  60.     if ball.y - rad < 0:
  61.         ball.y = rad
  62.         v.y = -v.y
  63.    
  64.     PDS.fill(0)
  65.     if pressed and dist > rad:
  66.         pygame.draw.line(PDS, RED, ball, mp)
  67.     pygame.draw.circle(PDS, WHITE, ball, rad)
  68.    
  69.     pygame.display.update()
  70.    
Add Comment
Please, Sign In to add comment