tesh-Intersections
Here’s the sketch:
Here’s the GIF:
And here’s my code!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | var lines = []; var lines = []; var numLines = 12; var len = 240; var intSize = 30; var bg = 200; var xborder = len/2; var yborder = len/5; //Intersection variables var intx = 0.0; var inty = 0.0; function setup() { createCanvas(720, 480); fill('rgba(180,243,255, 0.35)') background(bg); } function draw() { background(bg); if(lines.length > 1){ for(var i=0; i<numLines; i++){ var x1 = lines[i][0]; var y1 = lines[i][1]; var x2 = lines[i][2]; var y2 = lines[i][3]; for(var j=0; j<numLines; j++){ if(j!=i){ var x3 = lines[j][0]; var y3 = lines[j][1]; var x4 = lines[j][2]; var y4 = lines[j][3]; intx = 0.0; inty = 0.0; intersectionPt(x1,x2,x3,x4,y1,y2,y3,y4,intx,inty) if (intx > 0 && inty > 0){ noStroke(); ellipse(intx,inty,intSize,intSize); } } stroke(0); line(x1,y1,x2,y2); } } } } //Generates random lines whenever the mouse is clicked function mousePressed(){ lines = []; for(var i=0; i<numLines; i++){ var x1 = random(xborder,width-xborder); var y1 = random(height-yborder); var x2 = random(x1-len,x1+len); var y2 = sqrt(sq(len) - sq(x2-x1))+y1; lines.push([x1,y1,x2,y2]); } } //Code heavily taken from Example Code and Explanations by Paul Bourke at http://paulbourke.net/geometry/pointlineplane/ // //Function to test for intersections between line segments: function intersectionPt(x1,x2,x3,x4,y1,y2,y3,y4){ var uA,uB; var den,numA,numB; den = (y4-y3) * (x2-x1) - (x4-x3) * (y2-y1); numA = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3); numB = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3); //Coincident? - If true, displays intersection in center of line segment if (abs(numA) == 0 && abs(numB) == 0 && abs(den) == 0) { intx = (x1 + x2) / 2; inty = (y1 + y2) / 2; return(true); } //Parallel? - No intersection if (abs(den) == 0) { intx = 0; inty = 0; return(false); } //Intersection? uA = numA / den; uB = numB / den; //If both lie w/in the range of 0 to 1 then the intersection point is within both line segments. if (uA < 0 || uA > 1 || uB < 0 || uB > 1) { intx = 0; inty = 0; return(false); } intx = x1 + uA * (x2 - x1); inty = y1 + uA * (y2 - y1); return(true); } |