-
Notifications
You must be signed in to change notification settings - Fork 0
/
sensor.js
95 lines (79 loc) · 2.64 KB
/
sensor.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
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
class Sensors{
constructor(car, rayCount, spread){
this.car = car
this.rayCount = rayCount
this.rayLength = 250
this.raySpread = spread * Math.PI / 6
this.rays = []
this.readings = []
}
update(roadBorders, traffic){
this.#castRays()
this.readings = []
this.rays.forEach(ray => {
this.readings.push(this.#getReadings(ray, roadBorders, traffic))
})
}
#getReadings(ray, borders, traffic){
let touches = []
borders.forEach(border => {
const touch = getIntersection(ray[0], ray[1], border[0], border[1])
if(touch)
touches.push(touch)
})
for(let i = 0 ; i < traffic.length; ++i){
for(let j = 0 ; j < traffic[i].length ; ++j){
const poly = traffic[i][j].polygon
for(let j = 0 ; j < poly.length ; ++j){
const touch = getIntersection(ray[0], ray[1], poly[j], poly[(j+1)%poly.length])
if(touch){
touches.push(touch)
}
}
}
}
if(touches.length == 0)
return null
else{
let offsets = touches.map(e => e.offset)
let minOffset = Math.min(...offsets)
return touches.find(e => e.offset == minOffset)
}
}
#castRays(){
this.rays = []
for(let i = 0 ; i < this.rayCount ; ++i){
let angle = lerp(
this.raySpread/2,
-this.raySpread/2,
this.rayCount == 1 ? 0.5 : i/(this.rayCount - 1)
) + this.car.angle
const start = {x : this.car.x, y : this.car.y}
const end = {
x : this.car.x - Math.sin(angle) * this.rayLength,
y : this.car.y - Math.cos(angle) * this.rayLength
}
this.rays.push([start, end])
}
}
draw(ctx){
ctx.lineWidth = 2
for(let i = 0 ; i < this.rays.length ; ++i){
let end = this.rays[i][1]
if(this.readings[i]){
end = this.readings[i]
}
ctx.lineWidth = 2
ctx.strokeStyle ="lightGray"
ctx.beginPath();
ctx.moveTo(this.rays[i][0].x, this.rays[i][0].y)
ctx.lineTo(end.x, end.y)
ctx.stroke()
ctx.strokeStyle = "black"
ctx.beginPath()
ctx.moveTo(this.rays[i][1].x, this.rays[i][1].y)
ctx.lineTo(end.x, end.y)
ctx.stroke()
}
}
}