-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspace.py
More file actions
61 lines (46 loc) · 1.77 KB
/
space.py
File metadata and controls
61 lines (46 loc) · 1.77 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
from body import Body
from collision import collide
def intersect_aabb(body_a, body_b):
a_min_x, a_min_y, a_max_x, a_max_y = body_a.aabb
b_min_x, b_min_y, b_max_x, b_max_y = body_b.aabb
return (
a_min_x <= b_max_x and
a_max_x >= b_min_x and
a_min_y <= b_max_y and
a_max_y >= b_min_y
)
class Space:
def __init__(self, bodies: list[Body], gravity = 9.8):
self.bodies: list[Body] = bodies
self.gravity = gravity
self._contact_points = []
def add(self, body: Body):
self.bodies.append(body)
def simulate_gravity(self, dt):
for body in self.bodies:
if body.is_static == False:
body.velocity[1] -= self.gravity * dt
def update_position(self, dt):
for body in self.bodies:
if body.is_static == False:
body.pos += body.velocity * dt
body.angle += body.angular_velocity * dt
def handle_collisions(self):
self._contact_points = []
for i in range(len(self.bodies) - 1):
for j in range(i + 1, len(self.bodies)):
if self.bodies[i] == self.bodies[j]:
continue
if not intersect_aabb(self.bodies[i], self.bodies[j]):
continue
contact_points = collide(self.bodies[i], self.bodies[j])
if contact_points is None:
continue
for point in contact_points:
if point is None:
continue
self._contact_points.append(point)
def step(self, dt):
self.simulate_gravity(dt)
self.update_position(dt)
self.handle_collisions()