-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathcollision_detection.py
More file actions
341 lines (292 loc) · 9.36 KB
/
collision_detection.py
File metadata and controls
341 lines (292 loc) · 9.36 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""
Collision detection algorithms for 2D geometric shapes.
Collision detection is a fundamental concept in computational geometry, physics
simulations, and game development. It determines whether two or more geometric
objects intersect or overlap in space.
This module implements several common 2D collision detection algorithms:
- Axis-Aligned Bounding Box (AABB) collision detection
- Circle-circle collision detection
- Circle-AABB collision detection
- Point-in-rectangle detection
- Point-in-circle detection
Reference: https://en.wikipedia.org/wiki/Collision_detection
Reference: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
"""
from __future__ import annotations
from math import sqrt
def is_aabb_collision(
x1: float,
y1: float,
w1: float,
h1: float,
x2: float,
y2: float,
w2: float,
h2: float,
) -> bool:
"""
Check if two Axis-Aligned Bounding Boxes (AABBs) are colliding.
Each rectangle is defined by its top-left corner (x, y), width (w),
and height (h).
>>> is_aabb_collision(0, 0, 10, 10, 5, 5, 10, 10)
True
>>> is_aabb_collision(0, 0, 10, 10, 20, 20, 10, 10)
False
>>> is_aabb_collision(0, 0, 10, 10, 10, 0, 10, 10)
False
>>> is_aabb_collision(0, 0, 5, 5, 3, 3, 5, 5)
True
>>> is_aabb_collision(-5, -5, 10, 10, 0, 0, 10, 10)
True
>>> is_aabb_collision(0, 0, -1, 10, 5, 5, 10, 10)
Traceback (most recent call last):
...
ValueError: Width and height must be non-negative
>>> is_aabb_collision(0, 0, 10, 10, 5, 5, -1, 10)
Traceback (most recent call last):
...
ValueError: Width and height must be non-negative
"""
if w1 < 0 or h1 < 0 or w2 < 0 or h2 < 0:
raise ValueError("Width and height must be non-negative")
return x1 < x2 + w2 and x1 + w1 > x2 and y1 < y2 + h2 and y1 + h1 > y2
def is_circle_collision(
cx1: float,
cy1: float,
r1: float,
cx2: float,
cy2: float,
r2: float,
) -> bool:
"""
Check if two circles are colliding.
Each circle is defined by its center (cx, cy) and radius (r).
>>> is_circle_collision(0, 0, 5, 8, 0, 5)
True
>>> is_circle_collision(0, 0, 5, 20, 20, 5)
False
>>> is_circle_collision(0, 0, 10, 5, 5, 10)
True
>>> is_circle_collision(0, 0, 1, 3, 0, 1)
False
>>> is_circle_collision(0, 0, 0, 0, 0, 0)
False
>>> is_circle_collision(0, 0, -1, 5, 5, 3)
Traceback (most recent call last):
...
ValueError: Radius must be non-negative
"""
if r1 < 0 or r2 < 0:
raise ValueError("Radius must be non-negative")
distance_squared = (cx2 - cx1) ** 2 + (cy2 - cy1) ** 2
radius_sum = r1 + r2
return distance_squared < radius_sum**2
def is_circle_aabb_collision(
cx: float,
cy: float,
radius: float,
rx: float,
ry: float,
rw: float,
rh: float,
) -> bool:
"""
Check if a circle and an Axis-Aligned Bounding Box (AABB) are colliding.
The circle is defined by its center (cx, cy) and radius.
The rectangle is defined by its top-left corner (rx, ry), width (rw),
and height (rh).
>>> is_circle_aabb_collision(5, 5, 3, 0, 0, 10, 10)
True
>>> is_circle_aabb_collision(20, 20, 3, 0, 0, 10, 10)
False
>>> is_circle_aabb_collision(12, 5, 3, 0, 0, 10, 10)
True
>>> is_circle_aabb_collision(0, 0, 1, 5, 5, 10, 10)
False
>>> is_circle_aabb_collision(5, 5, -1, 0, 0, 10, 10)
Traceback (most recent call last):
...
ValueError: Radius must be non-negative
>>> is_circle_aabb_collision(5, 5, 3, 0, 0, -1, 10)
Traceback (most recent call last):
...
ValueError: Width and height must be non-negative
"""
if radius < 0:
raise ValueError("Radius must be non-negative")
if rw < 0 or rh < 0:
raise ValueError("Width and height must be non-negative")
closest_x = max(rx, min(cx, rx + rw))
closest_y = max(ry, min(cy, ry + rh))
distance_squared = (cx - closest_x) ** 2 + (cy - closest_y) ** 2
return distance_squared < radius**2
def is_point_in_rectangle(
px: float,
py: float,
rx: float,
ry: float,
rw: float,
rh: float,
) -> bool:
"""
Check if a point is inside an Axis-Aligned Bounding Box (rectangle).
The point is defined by (px, py).
The rectangle is defined by its top-left corner (rx, ry), width (rw),
and height (rh).
>>> is_point_in_rectangle(5, 5, 0, 0, 10, 10)
True
>>> is_point_in_rectangle(15, 15, 0, 0, 10, 10)
False
>>> is_point_in_rectangle(0, 0, 0, 0, 10, 10)
True
>>> is_point_in_rectangle(10, 10, 0, 0, 10, 10)
False
>>> is_point_in_rectangle(-1, 5, 0, 0, 10, 10)
False
>>> is_point_in_rectangle(5, 5, 0, 0, -1, 10)
Traceback (most recent call last):
...
ValueError: Width and height must be non-negative
"""
if rw < 0 or rh < 0:
raise ValueError("Width and height must be non-negative")
return rx <= px < rx + rw and ry <= py < ry + rh
def is_point_in_circle(
px: float,
py: float,
cx: float,
cy: float,
radius: float,
) -> bool:
"""
Check if a point is inside a circle.
The point is defined by (px, py).
The circle is defined by its center (cx, cy) and radius.
>>> is_point_in_circle(3, 4, 0, 0, 10)
True
>>> is_point_in_circle(10, 10, 0, 0, 5)
False
>>> is_point_in_circle(0, 0, 0, 0, 1)
True
>>> is_point_in_circle(5, 0, 0, 0, 5)
False
>>> is_point_in_circle(3, 4, 0, 0, -1)
Traceback (most recent call last):
...
ValueError: Radius must be non-negative
"""
if radius < 0:
raise ValueError("Radius must be non-negative")
distance_squared = (px - cx) ** 2 + (py - cy) ** 2
return distance_squared < radius**2
def detect_all_collisions(
objects: list[dict],
) -> list[tuple[int, int]]:
"""
Detect all pairwise collisions among a list of geometric objects.
Each object is a dictionary with a 'type' key ('circle' or 'rect') and
the corresponding geometric parameters.
Circle: {'type': 'circle', 'cx': float, 'cy': float, 'r': float}
Rectangle: {'type': 'rect', 'x': float, 'y': float, 'w': float, 'h': float}
Returns a list of tuples (i, j) where objects[i] and objects[j] collide.
>>> objects = [
... {'type': 'circle', 'cx': 0, 'cy': 0, 'r': 5},
... {'type': 'circle', 'cx': 3, 'cy': 0, 'r': 5},
... {'type': 'circle', 'cx': 100, 'cy': 100, 'r': 1},
... ]
>>> detect_all_collisions(objects)
[(0, 1)]
>>> objects = [
... {'type': 'rect', 'x': 0, 'y': 0, 'w': 10, 'h': 10},
... {'type': 'rect', 'x': 5, 'y': 5, 'w': 10, 'h': 10},
... {'type': 'circle', 'cx': 20, 'cy': 20, 'r': 3},
... ]
>>> detect_all_collisions(objects)
[(0, 1)]
>>> detect_all_collisions([])
[]
"""
collisions: list[tuple[int, int]] = []
for i in range(len(objects)):
for j in range(i + 1, len(objects)):
if _check_collision(objects[i], objects[j]):
collisions.append((i, j))
return collisions
def _check_collision(obj1: dict, obj2: dict) -> bool:
"""
Check collision between two geometric objects.
>>> _check_collision(
... {'type': 'circle', 'cx': 0, 'cy': 0, 'r': 5},
... {'type': 'circle', 'cx': 3, 'cy': 0, 'r': 5},
... )
True
>>> _check_collision(
... {'type': 'rect', 'x': 0, 'y': 0, 'w': 10, 'h': 10},
... {'type': 'rect', 'x': 20, 'y': 20, 'w': 5, 'h': 5},
... )
False
"""
type1, type2 = obj1["type"], obj2["type"]
if type1 == "circle" and type2 == "circle":
return is_circle_collision(
obj1["cx"],
obj1["cy"],
obj1["r"],
obj2["cx"],
obj2["cy"],
obj2["r"],
)
if type1 == "rect" and type2 == "rect":
return is_aabb_collision(
obj1["x"],
obj1["y"],
obj1["w"],
obj1["h"],
obj2["x"],
obj2["y"],
obj2["w"],
obj2["h"],
)
if type1 == "circle" and type2 == "rect":
return is_circle_aabb_collision(
obj1["cx"],
obj1["cy"],
obj1["r"],
obj2["x"],
obj2["y"],
obj2["w"],
obj2["h"],
)
if type1 == "rect" and type2 == "circle":
return is_circle_aabb_collision(
obj2["cx"],
obj2["cy"],
obj2["r"],
obj1["x"],
obj1["y"],
obj1["w"],
obj1["h"],
)
msg = f"Unknown object types: {type1}, {type2}"
raise ValueError(msg)
if __name__ == "__main__":
import doctest
doctest.testmod()
print("AABB collision:", is_aabb_collision(0, 0, 10, 10, 5, 5, 10, 10))
print("Circle collision:", is_circle_collision(0, 0, 5, 8, 0, 5))
print("Point in rect:", is_point_in_rectangle(5, 5, 0, 0, 10, 10))
print("Point in circle:", is_point_in_circle(3, 4, 0, 0, 10))
print(
"Circle-AABB collision:",
is_circle_aabb_collision(5, 5, 3, 0, 0, 10, 10),
)
print(
"Detect all:",
detect_all_collisions(
[
{"type": "circle", "cx": 0, "cy": 0, "r": 5},
{"type": "circle", "cx": 3, "cy": 0, "r": 5},
{"type": "rect", "x": 100, "y": 100, "w": 10, "h": 10},
]
),
)