├── README.md └── gravity.py /README.md: -------------------------------------------------------------------------------- 1 | # Gravity 2 | Gravity simulation created using Python with Pygame. 3 | 4 | YT: 5 | https://youtu.be/osLA4WFFsmE 6 | -------------------------------------------------------------------------------- /gravity.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | from math import cos, sin, sqrt 4 | from random import randrange 5 | 6 | import pygame 7 | 8 | WIDTH = 800 9 | HEIGHT = 800 10 | CENTER = WIDTH // 2, HEIGHT // 2 11 | centerX = WIDTH // 2 12 | centerY = HEIGHT // 2 13 | 14 | G = 0.2 15 | M = 10e7 16 | 17 | BLACK = (0, 0, 0) 18 | WHITE = (255, 255, 255) 19 | 20 | r0 = 10 21 | 22 | pygame.init() 23 | 24 | 25 | class Particle: 26 | def __init__(self, x, y): 27 | self.g = G 28 | self.mass = 2 29 | self.x = x 30 | self.y = y 31 | self.momentum_x = 500 32 | self.momentum_y = 500 33 | self.dt = 0.001 34 | 35 | def move(self, x_y_central_mass): 36 | x2 = x_y_central_mass[0] 37 | y2 = x_y_central_mass[1] 38 | hyp = (self.x - x2) ** 2 + (self.y - y2) ** 2 39 | theta = math.atan2(y2 - self.y, x2 - self.x) 40 | force = (self.g * self.mass * M) / hyp 41 | force_x = force * math.cos(theta) 42 | force_y = force * math.sin(theta) 43 | self.momentum_x += force_x * self.dt 44 | self.momentum_y += force_y * self.dt 45 | self.x += self.momentum_x / self.mass * self.dt 46 | self.y += self.momentum_y / self.mass * self.dt 47 | return [self.x, self.y] 48 | 49 | 50 | screen = pygame.display.set_mode((WIDTH, HEIGHT)) 51 | 52 | particles = [] 53 | 54 | r = 200 55 | 56 | 57 | # Line 58 | def generator(): 59 | for i in range(1000): 60 | x = randrange(-500, 1000) 61 | y = 100 62 | p = Particle(x, y) 63 | particles.append(p) 64 | 65 | 66 | # Circle 67 | # def generator(): 68 | # for i in range(1000): 69 | # ang = random.uniform(0, 1) * 2 * math.pi 70 | # hyp = sqrt(random.uniform(0, 1)) * r 71 | # adj = cos(ang) * hyp 72 | # opp = sin(ang) * hyp 73 | # x = centerX + adj 74 | # y = centerY + opp 75 | # p = Particle(x, y) 76 | # particles.append(p) 77 | 78 | 79 | # Square 80 | # def generator(): 81 | # for i in range(500): 82 | # x = randrange(0, 500) 83 | # y = randrange(0, 500) 84 | # p = Particle(x, y) 85 | # particles.append(p) 86 | 87 | 88 | generator() 89 | 90 | 91 | def draw(): 92 | for i in range(len(particles)): 93 | pygame.draw.circle(screen, WHITE, (particles[i].move(CENTER)), 1) 94 | 95 | 96 | running = True 97 | while running: 98 | 99 | for event in pygame.event.get(): 100 | if event.type == pygame.QUIT: 101 | running = False 102 | 103 | screen.fill(BLACK) 104 | 105 | # Gravity point 106 | # central_mass = pygame.draw.circle(screen, WHITE, CENTER, r0) 107 | 108 | draw() 109 | 110 | pygame.display.update() 111 | --------------------------------------------------------------------------------