xxxxxxxxxx
137
// Arthur Cavalcanti - 11/mar/2020
// Coding Challenge from CodingTrain
// Gift Wrapping Algorithm
// My own take!
let spacing;
let points;
let giftP;
let angle;
let currentP;
let nextPoint;
let leftMost;
let end;
let numOfPoints = 80; // Number of starting points
let speed = 0.005; // speed with which the angle changes
let precision = 100; // value threashold for the z during a cross product to be considered a parallel vector
function setup() {
createCanvas(windowWidth, windowHeight);
spacing = windowWidth * 0.05;
reset();
}
function draw() {
background(0);
fill(255);
noStroke();
frameRate(30);
for (let i = 0; i < points.length; i++) {
ellipse(points[i].x, points[i].y, 4, 4);
}
stroke(255);
strokeWeight(3);
if(end) {
fill(0,255,100,10);
}else{
noFill()
}
beginShape();
for (let i = 0; i < giftP.length; i++) {
vertex(giftP[i].x, giftP[i].y);
}
endShape();
if (!end) {
for (let i = 0; i < giftP.length; i++) {
fill(255, 0, 255);
ellipse(giftP[i].x, giftP[i].y, 8, 8);
}
push();
translate(currentP.x, currentP.y);
let x = -100 * cos(angle);
let y = -100 * sin(angle);
let currentV = createVector(x, y);
stroke(0, 255, 0, 255);
strokeWeight(2);
line(0, 0, x, y);
for (let i = 0; i < points.length; i++) {
let px = points[i].x - currentP.x;
let py = points[i].y - currentP.y;
let cp = createVector(px, py);
stroke(0, 255, 120, 50);
strokeWeight(1);
line(0, 0, px, py);
let a = p5.Vector.cross(currentV, cp);
if (abs(a.z) < precision && px != 0 && (points[i] != leftMost || giftP.length > 3)) {
console.log("precision = " + abs(a.z));
nextPoint = points[i];
if (nextPoint != leftMost) {
points.splice(i, 1);
} else {
console.log("END");
end = true;
}
break;
}
}
pop();
angle += speed;
if (nextPoint != null) {
currentP = nextPoint;
giftP.push(currentP);
nextPoint = null;
} else if (end) {
currentP = leftMost;
}
} else {
setTimeout(reset, 3000);
}
}
function reset() {
giftP = [];
points = [];
nextPoint = null;
currentP = null;
leftMost = createVector(width + spacing, 0);
angle = PI / 2
for (let i = 0; i < numOfPoints; i++) {
let x = floor(random(spacing, width - spacing));
let y = floor(random(spacing, height - spacing));
let point = createVector(x, y);
points.push(point);
if (point.x < leftMost.x) {
leftMost = point;
}
}
giftP.push(leftMost);
currentP = leftMost;
end = false;
}