// First, create each line // - line is constrained in length, and saved as [x1,y1],[x2,y2] // - draw the line // Second, for each line, run algorithm to find int point // - save point to point masterlist // - draw point masterlist var boolDoRefresh; var numLinesSlider; var lineLengthSlider; function setup() { createCanvas(720, 400); numLinesSlider = createSlider(0,50,10); numLinesSlider.position(20,20); lineLengthSlider = createSlider(0,400,200); lineLengthSlider.position(20,40); background(255); boolDoRefresh = true; } function draw() { if (boolDoRefresh) { background(204, 255, 204) var lines = []; var lineLength = lineLengthSlider.value(); var numLines = numLinesSlider.value(); text("Number of Lines = "+ numLines.toString(), 30 + numLinesSlider.width, 35); text("Line Length = "+ lineLength.toString(), 30 + lineLengthSlider.width, 55); for (var i = 0; i < numLines; i++) { var curLine = makeLine(lineLength); lines.push(curLine); push(); stroke(102, 204, 255); strokeWeight(2); line(curLine[0][0], curLine[0][1], curLine[1][0], curLine[1][1]); pop(); } var points = []; for (var j = 0; j < lines.length; j++) { for (var k = 0; k < lines.length; k++) { if (j === k) { continue; } else { var line1 = lines[j]; var line2 = lines[k]; var curPoint = findIntersection(line1, line2); if (curPoint != false) { points.push(curPoint); push(); noStroke(); fill(255, 153, 0,50); ellipse(curPoint[0], curPoint[1], 20, 20); pop(); } } } } var numIntersections = points.length; text("Intersections: "+ numIntersections.toString(),625,380); boolDoRefresh = false; } } function mousePressed() { boolDoRefresh = true; } function makeLine(length) { var x1 = random(length, width - length); var y1 = random(length, height - length); var randAngle = Math.round(random(0, 360)); var xLength = Math.cos(randAngle) * length; var yLength = Math.sin(randAngle) * length; var x2 = x1 + xLength; var y2 = y1 + yLength; var curLine = [ [x1, y1], [x2, y2] ]; return curLine; } function findIntersection(line1, line2) { // line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/ // Determine the intersection point of two line segments var x1 = line1[0][0] var y1 = line1[0][1] var x2 = line1[1][0] var y2 = line1[1][1] var x3 = line2[0][0] var y3 = line2[0][1] var x4 = line2[1][0] var y4 = line2[1][1] var denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)) if (denominator === 0) { return false; } var ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator var ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false; } var x = x1 + ua * (x2 - x1) var y = y1 + ua * (y2 - y1) return [x, y]; } |