Skip to content

Commit 50b0531

Browse files
committed
added collision detection between primitives like circle, rectangle etc in physics
1 parent c0ad5bb commit 50b0531

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

physics/collision_detection.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Circle:
2+
def __init__(self, x, y, radius):
3+
self.x = x
4+
self.y = y
5+
self.radius = radius
6+
7+
8+
class Rectangle:
9+
def __init__(self, x, y, width, height):
10+
self.x = x
11+
self.y = y
12+
self.width = width
13+
self.height = height
14+
15+
16+
class CollisionDetection:
17+
@staticmethod
18+
def circle_circle_collision(circle1, circle2):
19+
dx = circle1.x - circle2.x
20+
dy = circle1.y - circle2.y
21+
distance_squared = dx**2 + dy**2
22+
radius_sum = circle1.radius + circle2.radius
23+
return distance_squared <= radius_sum**2
24+
25+
@staticmethod
26+
def rectangle_rectangle_collision(rect1, rect2):
27+
return not (
28+
rect1.x + rect1.width < rect2.x
29+
or rect1.x > rect2.x + rect2.width
30+
or rect1.y + rect1.height < rect2.y
31+
or rect1.y > rect2.y + rect2.height
32+
)
33+
34+
@staticmethod
35+
def circle_rectangle_collision(circle, rect):
36+
closest_x = max(rect.x, min(circle.x, rect.x + rect.width))
37+
closest_y = max(rect.y, min(circle.y, rect.y + rect.height))
38+
dx = circle.x - closest_x
39+
dy = circle.y - closest_y
40+
return dx**2 + dy**2 <= circle.radius**2

0 commit comments

Comments
 (0)