-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRay.pde
96 lines (88 loc) · 2.02 KB
/
Ray.pde
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
class Ray {
private float angle;
private PVector origin;
private PVector direction;
Ray(PVector origin, float angle) {
this.angle = angle;
this.origin = origin;
this.direction = PVector.fromAngle(angle);
}
PVector cast(LineBoundary line) {
float t = this.calculateT(
line.pt1.x,
line.pt1.y,
line.pt2.x,
line.pt2.y,
this.origin.x,
this.origin.y,
this.origin.x + this.direction.x,
this.origin.y + this.direction.y
);
float u = this.calculateU(
line.pt1.x,
line.pt1.y,
line.pt2.x,
line.pt2.y,
this.origin.x,
this.origin.y,
this.origin.x + this.direction.x,
this.origin.y + this.direction.y
);
Boolean intersectBoundary = t > 0 && t < 1 && u > 0;
if (intersectBoundary) {
return this.calculateIntersection(
line.pt1.x,
line.pt1.y,
line.pt2.x,
line.pt2.y,
t
);
}
return null;
}
private PVector calculateIntersection(
float x1,
float y1,
float x2,
float y2,
float t
) {
float x = x1 + t * (x2 - x1);
float y = y1 + t * (y2 - y1);
return new PVector(x, y);
}
private float calculateU(
float x1,
float y1,
float x2,
float y2,
float x3,
float y3,
float x4,
float y4
) {
float denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (denominator == 0) {
return -1;
}
float numerator = (x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2);
return numerator / denominator;
}
private float calculateT(
float x1,
float y1,
float x2,
float y2,
float x3,
float y3,
float x4,
float y4
) {
float denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (denominator == 0) {
return -1;
}
float numerator = (x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4);
return numerator / denominator;
}
}