-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathray.pyx
61 lines (51 loc) · 1.85 KB
/
ray.pyx
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
import math
class Ray:
def __init__(self, start, end):
"""
Initialize the ray line
:param start: The start position of the ray line
:param end: The end position of the ray line
"""
self.start = start
self.end = end
self.intersecting_walls = []
def cast(self, walls):
"""
Cast the rays to the walls and check for intersection
:param walls: The walls for the ray to cast
:return: Returns position of the closest intersection. Returns None, if no intersection
"""
record = float('inf')
closest = None
for wall in walls:
wall.intersecting = False
x1, y1 = wall.start
x2, y2 = wall.end
x3, y3 = self.start
x4, y4 = self.end
den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if den != 0:
try:
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den
except ZeroDivisionError:
t = 0
u = 0
intersecting = 0 < t < 1 and u > 0
if intersecting:
wall.intersecting = True
self.intersecting_walls.append(wall)
px, py = x1 + t * (x2 - x1), y1 + t * (y2 - y1)
d = self.point_dist(px, py)
if d < record:
record = d
closest = (px, py)
return closest
def point_dist(self, px, py):
"""
Distance between two points
:param px: The x point
:param py: The y point
:return: Returns the distance
"""
return math.sqrt((self.start[0] - px) ** 2 + (self.start[1] - py) ** 2)