paukparl-Intersections

 sketch:

 

gif:

 

var NUM_LINES = 12;
var LINE_LENGTH = 300;
var ELLIPSE_SIZE = 20;
var justClicked = true;
var lines;
 
function setup() {
  createCanvas(720, 480);
  strokeWeight(2);
  fill('rgba(30,30,40, 0.9)');
}
 
function draw() {
  if (justClicked) {
 
    // array refreshed upon click
    lines = [];
 
    // redraw upon click
    background(100, 100, 110);
    for (var i=0; i<NUM_LINES; i++) { drawRandLine(); } } justClicked = false; } // draw a random line function drawRandLine() { var randRotation = random(PI); var pointL = createVector( -LINE_LENGTH/2 * cos(randRotation), -LINE_LENGTH/2 * sin(randRotation) ); var pointR = createVector( LINE_LENGTH/2 * cos(randRotation), LINE_LENGTH/2 * sin(randRotation) ); if (randRotation > PI/2) {
    var pointTemp = pointL.copy();
    pointL = pointR;
    pointR = pointTemp;
  }
 
  var randTransX = random(width);
  var randTransY = random(height);
  pointL.add(randTransX, randTransY);
  pointR.add(randTransX, randTransY);
 
  stroke(255);
  line(pointL.x, pointL.y, pointR.x, pointR.y);
 
  var newLine = [pointL, pointR];
  checkIntersect(newLine);
  append(lines, newLine);
}
 
 
// check for intersections between new line and existing ones
function checkIntersect( lineB ) { 
 
  // go through lines already drawn on canvas
  for (var i=0; i<lines.length; i++) {
    var lineA = lines[i];
 
    // conduct Bourke intersection calculation
    var intersect = bourkeIntersect(
      lineA[0].x, lineA[0].y,
      lineA[1].x, lineA[1].y,
      lineB[0].x, lineB[0].y,
      lineB[1].x, lineB[1].y
    );
 
    if (intersect) {
      print("INTERSECTED!\n");
      noStroke();
      ellipse(intersect.x, intersect.y, ELLIPSE_SIZE);
    }
  }
}
 
 
// line intercept math by Paul Bourke http://paulbourke.net/geometry/pointlineplane/
// JS version by Leo Bottaro
function bourkeIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
  var denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
 
  // if lines are parallel
	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;
 
  // is the intersection along the segments
  if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
		return false;
	}
 
  // if intersect
  return createVector(x1 + ua * (x2 - x1), y1 + ua * (y2 - y1));
}
 
function mousePressed() {
  justClicked = true;
}