-
Notifications
You must be signed in to change notification settings - Fork 0
/
physics.py
48 lines (40 loc) · 1.24 KB
/
physics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import numpy as np
from tqdm import trange
class Body:
def __init__(
self,
position: np.ndarray,
velocity: np.ndarray,
radius: float,
mass: float,
color=(0, 255, 0),
):
self.position = position
self.velocity = velocity
self.radius = radius
self.mass = mass
self.color = color
class Space2D:
def __init__(self):
self.bodies = []
self.G = 6.67430e-11
def gravitational_force(self, body1, body2):
r = body2.position - body1.position
r_mag = np.linalg.norm(r)
r_hat = r / r_mag
force_mag = self.G * body1.mass * body2.mass / (r_mag**2)
return force_mag * r_hat
def total_force(self, body):
net_force = np.zeros(2)
for other_body in self.bodies:
if body != other_body:
net_force += self.gravitational_force(body, other_body)
return net_force
def update(self, dt):
for body in self.bodies:
net_force = self.total_force(body)
acceleration = net_force / body.mass
body.velocity += acceleration * dt
body.position += body.velocity * dt
def add_body(self, body):
self.bodies.append(body)