xxxxxxxxxx
42
class Ray {
constructor (x, y) {
this.pos = createVector(x, y);
this.dir = createVector(1,0);
}
lookAt(x, y) {
turir = createVector(x - this.pos.x, y - this.pos.y);
this.dir.normalize();
}
turnTo(deg) {
let r = radians(deg);
this.dir = createVector(cos(r), sin(r));
this.dir.normalize();
}
cast(segment) {
const x1 = segment.a.x;
const y1 = segment.a.y;
const x2 = segment.b.x;
const y2 = segment.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 denominator = ((x1 - x2)*(y3 - y4) - (y1 - y2)*(x3 - x4));
if(denominator == 0) { return false; } //lines parallel
let t = ((x1 - x3)*(y3 - y4) - (y1 - y3)*(x3 - x4)) / denominator;
let u = -((x1 - x2)*(y1 - y3) - (y1 - y2)*(x1 - x3)) / denominator;
if(!(t > 0 && t < 1 && u > 0)) { return false; }
return createVector(
x3 + u * (x4 - x3),
y3 + u * (y4 - y3)
);
}
}