xxxxxxxxxx
66
// Date: 8/26/19
// Description: this program creates random lines and highlights where they intersect. New lines are generated when the mouse is clicked.
// Equations identifying points of intersection reference Paul Bourke's derivations found at:
// http://www-cs.ccny.cuny.edu/~wolberg/capstone/intersection/Intersection%20point%20of%20two%20lines.html
//stores coordinates of line endpoints
var x1 = [];
var y1 = [];
var x2 = [];
var y2 = [];
var lines = 12 // number of lines
//stores coordinates of intersections
var xInt;
var yInt;
function generateLines() {
for (i = 0; i < lines; i++) { // fill coordinate arrays with line endpoints
x1[i] = (random(0, width));
y1[i] = (random(0, height));
x2[i] = (random(0, width));
y2[i] = (random(0, height));
}
}
function setup() {
createCanvas(640, 480);
generateLines();
}
function draw() {
background(220);
//draw lines
for (var i = 0; i < lines; i++) {
line(x1[i], y1[i], x2[i], y2[i]);
for (j = 0; j < 12; j++) {
checkIntersection(x1[i], y1[i], x2[i], y2[i], x1[j], y1[j], x2[j], y2[j]);
}
}
}
function mouseClicked() {
generateLines();
}
//use endpoints of 2 lines to check for intersections
function checkIntersection(x1, y1, x2, y2, x3, y3, x4, y4) {
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 and 1, there is an intersection
if (0 < ua && ua < 1 && 0 < ub && ub < 1) {
//find coordinates of intersection
xInt = x1 + ua * (x2 - x1);
yInt = y1 + ua * (y2 - y1);
//draw circle at point
fill(0, 0, 10, 90);
ellipse(xInt, yInt, 25, 25);
}
}