xxxxxxxxxx
111
/*jshint esversion: 6 */
var lineAmount = 12;
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class LineClass {
constructor(start, end) {//constructor assumes these are points
this.start = start;
this.end = end;
}
}
function createLine() {
start = new Point(0, 0);
end = new Point(0, 0);
}
function setup() {
createCanvas(640, 480);
background(0);
}
function draw() { }
function mousePressed() {
background(0);
var slope1;
var yintercept1;
var slope2;
var yintercept2;
var intersectPt;
var arraylist = [];
//create and draw lines
for (var counter = 0; counter < lineAmount; counter++) {
//start
var tempPoint1 = new Point(2, 0);
var tempPoint2 = new Point(0, 0);
var lin = new LineClass(tempPoint1, tempPoint2);
lin.start.x = random(width);
lin.start.y = random(height);
//end
lin.end.x = random(width);
lin.end.y = random(height);
arraylist.push(lin);
stroke(0, 255, 0);
line(lin.start.x, lin.start.y, lin.end.x, lin.end.y);
}
for (counter = 0; counter < arraylist.length; counter++) {
//a "for in" loop didn't work here
FindIntersectingLineInArray(arraylist[counter], arraylist);
}
}
//we test every line and if it intersect with another line in arraylist we highliht that point
function FindIntersectingLineInArray(lineToTest, lineArrayList) {
var reference_Slope = 0;
var referenceY_Intecept = 0;
var slope = 0;
var yIntercept = 0;
var interseptPoint;
reference_Slope = (lineToTest.end.y - lineToTest.start.y) / (lineToTest.end.x - lineToTest.start.x);
referenceY_Intecept = lineToTest.start.y - lineToTest.start.x * reference_Slope;
for (counter = 0; counter < lineArrayList.length; counter++) {
//a "for in" loop didn't work here as well
slope = (lineArrayList[counter].end.y - lineArrayList[counter].start.y) / (lineArrayList[counter].end.x - lineArrayList[counter].start.x);
yIntercept = lineArrayList[counter].start.y - lineArrayList[counter].start.x * slope;
if (reference_Slope != slope) {
lineLine(lineToTest.start.x, lineToTest.start.y, lineToTest.end.x, lineToTest.end.y, lineArrayList[counter].start.x, lineArrayList[counter].start.y, lineArrayList[counter].end.x, lineArrayList[counter].end.y);
}
}
}
// LINE/LINE Jeffrey Thomas Line intersection collision math
function lineLine(x1, y1, x2, y2, x3, y3, x4, y4) {
// calculate the distance to intersection point
var uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
var uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
// if uA and uB are between 0-1, lines are colliding
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
//draw a circle where the lines meet
var intersectionX = x1 + (uA * (x2 - x1));
var intersectionY = y1 + (uA * (y2 - y1));
fill(255, 0, 0);
ellipse(intersectionX, intersectionY, 7, 7);
return true;
}
return false;
}