-
Notifications
You must be signed in to change notification settings - Fork 0
/
raycast.py
65 lines (53 loc) · 1.83 KB
/
raycast.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import dataclasses
from typing import List, Dict
import utils
from obj import Obj
from vectors import Vec2
@dataclasses.dataclass
class RayCastResult:
x_pos: float
y_pos: float
dist: float
obj: Obj | None
hit: bool
def ray_cast(x_pos, y_pos, a, max_length: int, world: List[Obj]) -> List[RayCastResult]:
cast = utils.cast_line(Vec2(x_pos, y_pos), a, max_length)
line = (x_pos, y_pos, cast.x, cast.y)
dists: Dict[float, Obj] = {}
for obj in world:
pos = utils.find_intersection(line, (obj.a.x, obj.a.y, obj.b.x, obj.b.y))
# pos = line[2], line[3]
if not pos:
continue
x, y = pos
dists[utils.distance_between_points(x, y, x_pos, y_pos)] = obj
if dists == {}:
return [RayCastResult(line[2], line[3], max_length, None, False)]
p = sorted(list(dists.keys()))
result = []
for m in p:
obj = dists[m]
x, y = utils.find_intersection(line, (obj.a.x, obj.a.y, obj.b.x, obj.b.y))
# x, y = cast
result.append(RayCastResult(x, y, m, obj, True))
return result
def ray_cast_vector(x_pos, y_pos, x_end_pos, y_end_pos, world: List[Obj]) -> float:
line = (x_pos, y_pos, x_end_pos, y_end_pos)
dists: Dict[float, Obj] = {}
for obj in world:
pos = utils.find_intersection(line, (*obj.a, *obj.b))
# pos = line[2], line[3]
if not pos:
continue
x, y = pos
dists[utils.distance_between_points(x, y, x_pos, y_pos)] = obj
if dists == {}:
return utils.distance_between_points(x_pos, y_pos, x_end_pos, y_end_pos)
p = sorted(list(dists.keys()))
result = []
for m in p:
obj = dists[m]
x, y = utils.find_intersection(line, (*obj.a, *obj.b))
# x, y = cast
result.append(RayCastResult(x, y, m, obj, True))
return result[0].dist