miyehn-Intersections
First assignment for this course! I’m excited >:D
Here’s the code for this assignment.
var lineNum = 12; var lines; var intersections; function setup() { createCanvas(720,480); noLoop(); } function draw() { background(255); stroke(0); strokeWeight(1); lines = new Array(); intersections = new Array(); for(var i=0; i<lineNum; i++) { lines.push(new Line); } //console.log(lines); //display lines and calculate intersections for(var i=0; i<lineNum; i++) { lines[i].display(); for(var j=i+1; j<lineNum; j++) { var l1 = lines[i]; var l2 = lines[j]; var x = (l2.b-l1.b)/(l1.m-l2.m); if (x>=l1.p.x && x<=l1.q.x && x>=l2.p.x && x<=l2.q.x) { intersections.push(createVector(x, l1.m*x+l1.b)); } } } //display intersections fill(255,100,100,100); noStroke(); for(var i=0; i<intersections.length; i++) { ellipse(intersections[i].x,intersections[i].y,10,10); } } function mouseClicked() { redraw(); } class Line { constructor() { this.p = createVector(random(0,width),random(0,height)); this.q = createVector(random(0,width),random(0,height)); //this is to make sure p always holds the coord of the point on the left. if(this.p.x>this.q.x) { var tmp = this.p; this.p = this.q; this.q = tmp; } this.m = (this.q.y-this.p.y)/(this.q.x-this.p.x); this.b = this.p.y-(this.m * this.p.x); } display() { line(this.p.x,this.p.y,this.q.x,this.q.y); } } |