Hey, I watched this video by Daniel Shiffman and copied the code and changed it a bit. Now I only have one problem I want to connect the start and the end node to create a “real” shape. Anyone have an idea?
Here is my code:
PVector[] cities;
int totalCities = 40;
void setup() {
frameRate(30);
fullScreen();
//size(600, 600);
cities = new PVector[totalCities];
for (int i = 1; i < totalCities-1; i++) {
PVector v = new PVector(random(width), random(height));
cities[i] = v;
}
cities[0] = new PVector(10, 10);
cities[totalCities-1] = new PVector(width-10, height-10);
//cities[cities.length-1] = cities[0].copy();
//arrayCopy(cities, bestEver);
}
void draw() {
background(0);
fill(255);
for (int i = 0; i < cities.length; i++) {
ellipse(cities[i].x, cities[i].y, 8, 8);
}
stroke(255);
strokeWeight(1);
noFill();
beginShape();
for (int i = 0; i < cities.length; i++) {
vertex(cities[i].x, cities[i].y);
}
endShape();
//stroke(255, 0, 255);
//strokeWeight(4);
//noFill();
//beginShape();
//for (int i = 0; i < cities.length; i++) {
// vertex(bestEver[i].x, bestEver[i].y);
//}
//endShape();
for (int i = 0; i < cities.length-1; i++) {
PVector a = cities[i];
PVector b = cities[i+1];
for (int j = i + 2; j < cities.length-1; j++) {
PVector a2 = cities[j];
PVector b2 = cities[j+1];
if (lineLineCollision(a.x, a.y, b.x, b.y, a2.x, a2.y, b2.x, b2.y) == true) {
swap(cities, i, j);
}
}
}
}
//void mousePressed() {
// int indexI = floor(random(cities.length));
// int indexJ = floor(random(cities.length));
// swap(cities, indexI, indexJ);
//}
void keyPressed() {
setup();
}
void swap(PVector[] a, int i, int j) {
PVector temp = a[i];
a[i] = a[j];
a[j] = temp;
}
boolean lineLineCollision(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) {
// calculate the distance to intersection point
float uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
float 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) {
// optionally, draw a circle where the lines meet
//float intersectionX = x1 + (uA * (x2-x1));
//float intersectionY = y1 + (uA * (y2-y1));
//fill(255, 0, 0);
//noStroke();
//ellipse(intersectionX, intersectionY, 20, 20);
return true;
}
return false;
}