Lines are stored in point-slope form, intersections are calculated with slope-intercept form, and points are calculated using the parametric form.
I used lots of information from the p5.js website's Reference section, and lots of my knowledge of intersections comes from the Khan Academy Pixar in a Box Rendering series.
var slider; var lines; var tstep; var t; var intersections function setup() { createCanvas(720, 480); slider = createSlider(1,1000,10); slider.position(10, 10); t = 0; tstep = 2; angleMode(DEGREES); intersections = []; lines = [] recalculate(); stroke(255); strokeWeight(1) textSize(15); } function mouseReleased() { recalculate(); } function recalculate() { background(255); t = 0; var m1,m2,b1,b2,x,y,a1,a2,t1,t2,line1,line2; lines = [] intersections = [] for (var i = 0; i < slider.value(); i += 1) { lines.push([random(720), random(480), tan(random(-89,89))]) } for (var ln1 = 0; ln1 < lines.length - 1; ln1 += 1) { for (var ln2 = ln1+1; ln2 < lines.length; ln2 += 1) { line1 = lines[ln1]; line2 = lines[ln2]; m1 = line1[2]; m2 = line2[2]; b1 = line1[1]-m1*line1[0]; b2 = line2[1]-m2*line2[0]; x = (b2-b1)/(m1-m2); y = m1*x + b1; t1 = sqrt(pow(x-line1[0],2) + pow(y-line1[1],2)); t2 = sqrt(pow(x-line2[0],2) + pow(y-line2[1],2)); intersections.push([x,y,max(abs(t1),abs(t2))]); } } } function position(ln, T) { var a = 1 / sqrt(pow(ln[2],2)+1); var b = ln[0]; var c = sqrt(1-pow(a,2)) * abs(ln[2])/ln[2]; var d = ln[1]; return [a*T + b, c*T + d]; } function draw() { var p1, p2, intersection; t += 2; noStroke(); fill(0); for (var i = 0; i < intersections.length; i += 1) { intersection = intersections[i] if (abs(t) - tstep < intersection[2] && intersection[2] <= abs(t)) { ellipse(intersection[0], intersection[1], 10, 10); } } stroke(240,30,50); for (var j = 0; j < lines.length; j += 1) { ln = lines[j] p1 = position(ln, t); p2 = position(ln, -t) line(p1[0], p1[1], p2[0], p2[1]); } noStroke(); fill(0); rect(0,0,200,45); fill(255); text(slider.value(), 150, 27) } |