Hi, I am having trouble with finding the nearest neighbor points. I am trying to create a web of lines connecting randomly generated points to each other. these lines are supposed to connect the nearest points to each other. Something like this
Instead, my code is doing a sort of all lines connect to the same point. Im not sure how to fix this.
Point nodes = new Point[30];
float x1;
float x2;
float y1;
float y2;
float domain = 999999;
float dist;
int node1;
void setup(){
size(800,800);
background(255);
noFill();
strokeWeight(1);
//beginRecord(PDF, “PLan_Drawing.pdf”);
for(int i = 0; i < nodes.length; i++){
nodes[i] = new Point(random(width),random(height));
}
}
void draw(){
findNeighbours();
for (int i = 0; i < nodes.length; i++){
findNeighbours();
}
}
class Point {
float x;
float y;
Point (float x_, float y_){
x = x_;
y = y_;
}
}
void findNeighbours(){
for (int i = 0; i < nodes.length; i++){
for(int j = 0; j < nodes.length; j++){
if(i != j){
dist = dist(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y);
if(dist<domain){
domain = dist;
node1 = j;
}
}
if(j == nodes.length-1){
line(nodes[i].x, nodes[i].y, nodes[node1].x, nodes[node1].y);
}
}
}
}
Any help is appreciated