let lines = []; let slider; let intersectionsArray = []; let intersection = []; function setup() { createCanvas(720, 480); background(255, 204, 0); slider = createSlider(12, 100, 12); slider.position(50, 80); stroke(0,0,255); textSize(15); text('click to begin', width/2,height/2); } function mousePressed(){ intersectionsArray = []; lines = []; background(255, 204, 0); var lineNumber = slider.value(); for (var i = 0; i < lineNumber; i++){ var newLine = new Line(random(50,width-100), random(50, height-100), random(50,width-100), random(50, height-100)); lines.push(newLine); } for (i = 0; i < lines.length-1; i++){ for (var j = 1; j < lines.length; j++) { if (lines[i] !== lines[j]){ intersection = (intersect(lines[i].x1, lines[i].y1, lines[i].x2, lines[i].y2, lines[j].x1, lines[j].y1, lines[j].x2, lines[j].y2)); } if (intersection !== false && intersectionsArray.includes(intersection) == false){ intersectionsArray.push(intersection); } } } fill(255,0,0,50); text('number of lines:', 50,70); text(lines.length, 170,70); for (let l of lines){ l.drawLine(); } for (i = 0; i < intersectionsArray.length; i++) { ellipse(intersectionsArray[i][0], intersectionsArray[i][1],15); } } class Line { constructor(x1, y1, x2, y2){ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } drawLine(){ line (this.x1, this.y1, this.x2, this.y2); } } //intersection calculations from paul bourke and leo bottaro function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) { return false; } denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); if (denominator === 0) { return false; } let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator; let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false; } let x = x1 + ua * (x2 - x1); let y = y1 + ua * (y2 - y1); return [x, y] } |