xxxxxxxxxx
82
let refresh;
let lineList = [];
let lineCount = 10;
let canWidth;
let canHeight;
function setup() {
canWidth = 640;
canHeight = 480;
createCanvas(canWidth, canHeight);
refresh = true;
}
function draw() {
if (refresh) {
clear();
background(39, 94, 80);
lineList = [];
//draw lines
createLines(lineCount);
//find intersections + make a firefly
findIntersections();
refresh = false;
}
}
function mousePressed() {
refresh = true;
}
function createLines(lineCount) {
stroke(200);
for (i = 0; i < lineCount; i++) {
var point1 = {x: random(canWidth), y: random(canHeight)};
var point2 = {x: random(canWidth), y: random(canHeight)};
line(point1.x, point1.y, point2.x, point2.y);
var newLine = {P1: point1, P2: point2};
append(lineList, newLine);
}
}
function findIntersections() {
//variable for intersection must be initiated with some value
var intersect = {x: 0, y: 0};
for (i = 0; i < lineList.length; i++) {
for (j = i + 1; j < lineList.length; j++) {
var currentLine = lineList[i];
var compareLine = lineList[j];
if (getIntersection(currentLine, compareLine, intersect)) {
noStroke();
colorMode(RGB);
fill(color(255,50));
circle(intersect.x, intersect.y, 15, 120);
fill(color(255,100));
circle(intersect.x, intersect.y, 12, 120);
fill(color(255));
circle(intersect.x, intersect.y, 7);
}
}
}
}
function getIntersection(line1, line2, intersect) {
//denominator should be the same for both Ua and Ub
//(y4 - y3)(x2 - x1) - (x4 - x3)(y2 - y1)
var denominator = (line2.P2.y - line2.P1.y) * (line1.P2.x - line1.P1.x) - (line2.P2.x - line2.P1.x) * (line1.P2.y - line1.P1.y);
//check if lines are parallel
if (denominator == 0) return false;
var numerator1 = (line2.P2.x - line2.P1.x) * (line1.P1.y - line2.P1.y) - (line2.P2.y - line2.P1.y) * (line1.P1.x - line2.P1.x);
var numerator2 = (line1.P2.x - line1.P1.x) * (line1.P1.y - line2.P1.y) - (line1.P2.y - line1.P1.y) * (line1.P1.x - line2.P1.x);
if (Ua < 0 || Ub < 0) return false;
var Ua = numerator1 / denominator;
var Ub = numerator2 / denominator;
if (Ua > 1 || Ub > 1) return false;
//x = x1 + ua(x2 - x1)
//y = y1 + ua(y2 - y1)
intersect.x = line1.P1.x + Ua * (line1.P2.x - line1.P1.x);
intersect.y = line1.P1.y + Ua * (line1.P2.y - line1.P1.y);
//print("true");
return true;
}