-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathray.js
53 lines (44 loc) · 1.22 KB
/
ray.js
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
class Ray {
constructor(pos, angle) {
this.pos = pos;
this.dir = p5.Vector.fromAngle(angle);
}
lookAt(x, y) {
this.dir.x = x - this.pos.x;
this.dir.y = y - this.pos.y;
this.dir.normalize();
}
setPos(pos) {
this.pos = pos;
}
cast(wall) {
const x1 = wall.a.x;
const y1 = wall.a.y;
const x2 = wall.b.x;
const y2 = wall.b.y;
const x3 = this.pos.x;
const y3 = this.pos.y;
const x4 = this.pos.x + this.dir.x;
const y4 = this.pos.y + this.dir.y;
const den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if(den == 0) return;
const t = ( (x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4) ) / den;
const u = - ( (x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3) ) / den;
if(t >= 0 && t <= 1 && u >= 0) {
return {
'x': x1 + t * (x2 - x1),
'y': y1 + t * (y2 - y1),
'u': u
};
} else {
return;
}
}
show() {
stroke(255, 0, 0, 100);
push();
translate(this.pos.x, this.pos.y);
line(0, 0, this.dir.x * 10, this.dir.y * 10);
pop();
}
}