-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRay.js
66 lines (58 loc) · 1.23 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
54
55
56
57
58
59
60
61
62
63
64
65
66
class Ray
{
constructor(pos, angle)
{
this.pos = pos;
this.dir = p5.Vector.fromAngle(angle);
}
show()
{
stroke(255);
push();
translate(this.pos.x, this.pos.y);
line(0,0, this.dir.x*10, this.dir.y *10);
pop();
}
setAngle(angle)
{
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();
}
cast(wall)
{
const x1 = wall.a.x;
const y1 = wall.a.y;
const x2 = wall.b.x;
const y2 = wall.b.y;
//two points of the intersect line
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;
//calculate denominator
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;
//check for value of t and u for line intersection
if(t > 0 && t < 1 && u > 0)
{
const pt = createVector();
pt.x = x1 + t * (x2 - x1);
pt.y = y1 + t * (y2 - y1);
return pt
}
else
{
return;
}
}
}