Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Pragyanur committed Aug 11, 2023
1 parent 8b184c2 commit 1d66ce1
Showing 1 changed file with 72 additions and 15 deletions.
87 changes: 72 additions & 15 deletions scripts/ray-casting.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
class RAY {
constructor(x, y) {
this.position = createVector(x, y);
this.direction = createVector(1, 0);
constructor(angle) {
this.position = createVector(undefined, undefined);
this.direction = createVector(Math.sin(angle), Math.cos(angle));
this.point = createVector(undefined, undefined);
}

intersect(wall) {
const x1 = wall.A.x;
const y1 = wall.A.y;
Expand All @@ -11,36 +13,91 @@ class RAY {

const x3 = this.position.x;
const y3 = this.position.y;
const x4 = this.direction.x;
const y4 = this.direction.y;
const x4 = x3 + this.direction.x;
const y4 = y3 + this.direction.y;

const den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);


if (den == 0) {
return;
return false; // lines never meet
}

else {
const t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den;
const u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / den;
}
let t, u;

let p1, p2;
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den;
u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / den;

if(t >= 0 && t <= 1 && u >= 0) {
p1 = x1 + t * (x2 - x1);
p2 = y1 + t * (y2 - y1);
if (t >= 0 && t <= 1 && u >= 0) {
this.point.x = x1 + t * (x2 - x1);
this.point.y = y1 + t * (y2 - y1);
}
return createVector(p1, p2);
return (t >= 0 && t <= 1 && u >= 0);
}

show(wall) {
if (this.intersect(wall)) {
stroke(200, 70);
line(this.position.x, this.position.y, this.point.x, this.point.y);
}
}

updatePosition(x, y) {
this.position.x = x;
this.position.y = y;
}
}



class WALL {
constructor(x1, y1, x2, y2) {
this.A = createVector(x1, y1);
this.B = createVector(x2, y2);
}
show() {
stroke(200);
line(this.A.x, this.A.y, this.B.x, this.B.y);
}
}



let walls = [];
let rays = [];
const offset = 10;

function setup() {
createCanvas(windowWidth, windowHeight);
let wall = new WALL(100, 500, 600, 600);

let t = new WALL(offset, offset, width - offset, offset);
let r = new WALL(width - offset, offset, width - offset, height - offset);
let b = new WALL(offset, height - offset, width - offset, height - offset);
let l = new WALL(offset, offset, offset, height - offset);

walls.push(wall);
walls.push(t);
walls.push(r);
walls.push(b);
walls.push(l);

for (let angle = 0; angle < 2 * PI; angle += 0.063) {
let r = new RAY(angle);
rays.push(r);
}
}

function draw() {
background(0);
for (let wall of walls) {
wall.show();
}

for (let r of rays) {
r.updatePosition(mouseX, mouseY);
for (let wall of walls) {
r.show(wall);
}
}
}

0 comments on commit 1d66ce1

Please sign in to comment.