xxxxxxxxxx
125
class Fold{
constructor(start, maxFolds=10){
this.start = start;
this.points = [];
this.points.push(start);
this.maxFolds = maxFolds;
this.currentFolds = 0;
this.angles = [];
this.angleSubdivs = 2;
this.angleUnit = TWO_PI / this.angleSubdivs;
this.length = 50;
this.leapLength =10;
while(this.currentFolds < this.maxFolds){
let lastPoint = this.points[this.points.length - 1];
let angle = int(random(-this.angleSubdivs, this.angleSubdivs)) * this.angleUnit;
let p = p5.Vector.fromAngle(angle).setMag(this.length);
let newPoint = p5.Vector.add(lastPoint,p);
// Placing the second point or no intersections found
if(this.points.length == 1 || !this.doesIntersect(lastPoint, newPoint)){
this.points.push(newPoint);
this.currentFolds++;
}
else{
// Try a leap to the side Try first randomly left and then the other if it doesnt work ?
// Put the leap
let leftright = Math.random() < 0.5 ? PI/2 : -PI/2; // choose a random left or right angle
let q = p5.Vector.fromAngle(angle + leftright).setMag(this.leapLength);
let leapPoint = p5.Vector.add(lastPoint,q);
// Put the fold
let r = p5.Vector.fromAngle(angle + (leftright * 2)).setMag(this.length);
let afterPoint = p5.Vector.add(leapPoint,r);
if(!this.doesIntersect(leapPoint, afterPoint) && !this.doesIntersect(leapPoint, lastPoint)){
// Add both to array
this.points.push(leapPoint);
this.points.push(afterPoint);
this.currentFolds++;
}
}
}
}
doesIntersect(p,q){
for(let i = 1; i < this.points.length; i++){
let m = this.points[i];
let n = this.points[i-1];
return this.intersects(p.x,p.y,q.x,q.y,m.x,m.y,n.x,n.y);
}
}
// returns true if the line from (a,b)->(c,d) intersects with (p,q)->(r,s)
intersects(a,b,c,d,p,q,r,s) {
if(
(
Math.abs(a - p) < 0.1 &&
Math.abs(b - q) < 0.1 &&
Math.abs(c - r) < 0.1 &&
Math.abs(d - s) < 0.1
) ||
(
Math.abs(a - r) < 0.1 &&
Math.abs(b - s) < 0.1 &&
Math.abs(c - p) < 0.1 &&
Math.abs(d - q) < 0.1
)
){
return true;
}
// rest of the check
var det, gamma, lambda;
det = (c - a) * (s - q) - (r - p) * (d - b);
if (det === 0) {
return false;
} else {
lambda = ((s - q) * (r - a) + (p - r) * (s - b)) / det;
gamma = ((b - d) * (r - a) + (c - a) * (s - b)) / det;
return ((-0 < lambda && lambda < 1) && (-0 < gamma && gamma < 1));
}
}
draw(){
for(let i = 0; i < this.points.length - 1; i++){
let v = p5.Vector.sub(this.points[i], this.points[i+1]);
if(v.mag() <= this.leapLength + 2 ){ stroke('red') }
else{stroke(i*50)}
line(this.points[i].x, this.points[i].y, this.points[i+1].x, this.points[i+1].y);
}
}
}
function setup() {
createCanvas(600, 600);
frameRate(1);
}
function draw() {
background(130,150,235);
strokeWeight(2);
stroke(0);
let c = createVector(width/2,height/2);
let fold = new Fold(c);
fold.draw();
noLoop();
}