87 lines
2.9 KiB
JavaScript
Executable File
87 lines
2.9 KiB
JavaScript
Executable File
class Ray {
|
|
constructor(xorigin, yorigin, angle, sight) {
|
|
this.origin = createVector(xorigin, yorigin);
|
|
this.direction = p5.Vector.fromAngle(angle); //createVector(xdirection, ydirection);
|
|
this.length = sight;
|
|
this.hit = 0;
|
|
this.intersections = [];
|
|
this.closestIntersection;
|
|
}
|
|
|
|
show() {
|
|
if (this.hit >= 1) {
|
|
stroke(130);
|
|
line(this.origin.x, this.origin.y, this.closestIntersection.x, this.closestIntersection.y);
|
|
push();
|
|
noFill();
|
|
stroke(100);
|
|
strokeWeight(10);
|
|
ellipse(this.closestIntersection.x, this.closestIntersection.y, 7, 7);
|
|
pop();
|
|
} else {
|
|
push();
|
|
noFill();
|
|
stroke(75);
|
|
strokeWeight(1);
|
|
line(this.origin.x, this.origin.y, this.origin.x + this.direction.x * this.length, this.origin.y + this.direction.y * this.length);
|
|
//line(this.origin.x, this.origin.y, mouseX, mouseY);
|
|
pop();
|
|
}
|
|
|
|
}
|
|
|
|
cast(wall) {
|
|
if (wall) {
|
|
const x1 = this.origin.x;
|
|
const y1 = this.origin.y;
|
|
const x2 = this.origin.x + this.direction.x * this.length;
|
|
const y2 = this.origin.y + this.direction.y * this.length;
|
|
//const x2 = mouseX;
|
|
//const y2 = mouseY;
|
|
|
|
const x3 = wall.a.x;
|
|
const y3 = wall.a.y;
|
|
const x4 = wall.b.x;
|
|
const y4 = wall.b.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 && u <= 1) {
|
|
this.hit++;
|
|
this.intersections.push(createVector(x1 + t * (x2 - x1), y1 + t * (y2 - y1)));
|
|
}
|
|
this.distance = Infinity;
|
|
|
|
if (this.intersections && this.intersections.length) {
|
|
if (this.hit) {
|
|
for (let i = 0; i < this.intersections.length; i++) {
|
|
if (p5.Vector.dist(createVector(x1, y1), this.intersections[i]) < this.distance) {
|
|
this.closestIntersection = this.intersections[i];
|
|
this.distance = p5.Vector.dist(createVector(x1, y1), this.intersections[i])
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
|
|
if (this.hit >= 1)
|
|
return this.distance;
|
|
else
|
|
return null;
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
|
|
function distanceFromVectors(v1, v2) {
|
|
//var distance = abs(v1.x - v2.x) + abs(v1.y - v2.y)
|
|
var distance = sqrt(sq(v1.x - v2.x) + sq(v1.y - v2.y));
|
|
return distance;
|
|
} |