xxxxxxxxxx
116
var size = 500;
function setup() {
createCanvas(size+500, size);
background(220);
}
function getIntersection(r, s){
let r_px = r.a.x;
let r_py = r.a.y;
let r_dx = r.b.x - r.a.x;
let r_dy = r.b.y - r.a.y;
let s_px = s.a.x;
let s_py = s.a.y;
let s_dx = s.b.x - s.a.x;
let s_dy = s.b.y - s.a.y;
//Are they parallel?
if(r_dx*s_dy == r_dy*s_dx){
return null;
}
const T2 = (r_dx*(s_py-r_py) + r_dy*(r_px-s_px))/(s_dx*r_dy - s_dy*r_dx);
const T1 = (s_py+s_dy*T2-r_py)/r_dy;
if(T1 < 0){
return null;
}
if(T2 < 0 || T2 > 1){
return null;
}
return {
x: r_px+r_dx*T1,
y: r_py+r_dy*T1,
param: T1
};
}
var segs = [
//seg
{a: {x:20, y:300}, b: {x: 250, y: 150}},
{a: {x:200, y:300}, b: {x: 140, y: 100}},
{a: {x:250, y:150}, b: {x: 140, y: 100}},
{a: {x:320, y:300}, b: {x: 380, y: 300}},
{a: {x:380, y:300}, b: {x: 380, y: 360}},
{a: {x:380, y:360}, b: {x: 320, y: 360}},
{a: {x:320, y:360}, b: {x: 320, y: 300}},
//border
{a: {x:0, y:0}, b: {x: size, y: 0}},
{a: {x:0, y:0}, b: {x: 0, y: size}},
{a: {x:size, y:0}, b: {x: size, y: size}},
{a: {x:0, y:size}, b: {x: size, y: size}}
]
function draw() {
background(0);
stroke('red');
strokeWeight(1);
// for(let T1 = 0; T1 < 200; T1++){
// let ray_x = 20+1*T1;
// let ray_y = 30+1*T1;
// point(ray_x, ray_y);
// }
//line(ray.a.x, ray.a.y, mouseX, mouseY);
stroke('red');
for(let seg of segs){
line(seg.a.x, seg.a.y, seg.b.x, seg.b.y);
}
beginShape();
for(let j = 0; j < PI*2; j+=PI*2/50){
let ray = {a: {x: mouseX, y: mouseY}, b: {x: mouseX+sin(j), y: mouseY+cos(j)}};
//Finding the closest intersection
let closestIntersection = null;
for(let seg of segs){
let intersect = getIntersection(ray, seg);
if(!intersect) continue;
if(!closestIntersection || intersect.param < closestIntersection.param){
closestIntersection = intersect;
}
}
stroke('white');
if(closestIntersection){
line(ray.a.x, ray.a.y, closestIntersection.x, closestIntersection.y);
//line(ray.a.x, ray.a.y, closestIntersection.b.x, closestIntersection.b.y);
// vertex(closestIntersection.a.x, closestIntersection.a.y);
//vertex(closestIntersection.b.x, closestIntersection.b.y);
fill('white');
circle(closestIntersection.x, closestIntersection.y, 5);
}
}
endShape(CLOSE);
// stroke(0);
// for(let T2 = 0; T2 < 150; T2++){
// let s_dx = 1;
// let s_dy = -1;
// let seg_x = 20+s_dx*T2;
// let seg_y = 300+s_dy*T2;
// point(seg_x, seg_y);
// }
}