-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor.js
More file actions
91 lines (81 loc) · 2.62 KB
/
sensor.js
File metadata and controls
91 lines (81 loc) · 2.62 KB
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
class Sensor {
constructor({ cell = undefined, rayCount = 10, rayLength = 128 }) {
this.cell = cell;
if (cell instanceof Prey) {
this.rayCount = 9;
this.rayLength = 150;
this.raySpread = 4
} else {
this.rayCount = 6;
this.rayLength = 110;
this.raySpread = Math.PI / 3;
}
this.colors = new Array(this.rayCount).fill(0);
this.rays = [];
this.readings = [];
}
#castRays() {
this.rays = [];
for (let i = 0; i < this.rayCount; i++) {
const rayAngle = lerp(
this.raySpread / 2,
- this.raySpread / 2,
this.rayCount == 1 ? 0.5 : i / (this.rayCount - 1)
) + this.cell.pa;
const start = { x: this.cell.x, y: this.cell.y }
const end = {
x: this.cell.x +
Math.cos(rayAngle) * this.rayLength,
y: this.cell.y +
Math.sin(rayAngle) * this.rayLength
};
this.rays.push([start, end]);
}
}
#getReading(ray, nearCells) {
const collisions = [];
for (const cell of nearCells) {
if (cell === this.cell) continue;
let intersections = circleLineCollision(cell, ray);
if (intersections.length > 0) {
collisions.push(...intersections);
}
}
if (collisions.length === 0)
return null;
const offsets = collisions.map(c => c.offset);
const closest = Math.min(...offsets);
const closestCell = collisions.find(e => e.offset == closest)
return closestCell;
}
draw(ctx) {
for (let i = 0; i < this.rayCount; i++) {
let color = "aqua";
ctx.beginPath();
//let end = this.readings[i];
let end = this.rays[i][1];
if (this.readings[i]) {
end = this.readings[i];
color = "red"
}
ctx.lineWidth = 0.5;
ctx.strokeStyle = color;
ctx.moveTo(
this.rays[i][0].x,
this.rays[i][0].y
);
ctx.lineTo(
end.x,
end.y
);
ctx.stroke();
}
}
update(nearCells) {
this.#castRays();
this.readings = [];
for (let i = 0; i < this.rayCount; i++) {
this.readings.push(this.#getReading(this.rays[i], nearCells));
}
}
}