Hello, I am trying to create a code that will link circles to squares if they are within a specified distance, I obviously want to expand upon this later but for now this is my code.
int numBalls = 15;
int numSquares = 3;
int detection = 130;
ArrayList<Ball> balls = new ArrayList<Ball>();
ArrayList<Square> squares = new ArrayList<Square>();
void setup() {
size (600, 600);
for (int i = 0; i < numSquares; i++) {
squares.add(new Square(random(width), random(height)));
}
for (int i = 0; i < numBalls; i++) {
balls.add(new Ball(random(width), random(height)));
}
}
void draw() {
background(0);
for (Ball ball : balls) {
ball.display();
ball.update(squares);
}
for (Square square : squares) {
square.display();
}
}
class Ball {
PVector pos, npos;
float count;
boolean move;
boolean connected;
color col;
Square nearest = null;
Ball(float X, float Y) {
pos = new PVector(X, Y);
npos = new PVector(X, Y);
col = color(-1);
}
void display() {
fill(col);
noStroke();
ellipse(pos.x, pos.y, 15, 15);
if (connected) {
strokeWeight(2);
stroke(-1, 100);
line(pos.x, pos.y, nearest.pos.x, nearest.pos.y);
}
}
void update(ArrayList<Square> others) {
for (Square square : others) {
float d = dist(pos.x, pos.y, square.pos.x, square.pos.y);
if (d < detection) {
nearest = square;
connected = true;
} else {
connected = false;
}
}
}
}
class Square {
PVector pos;
Square(float X, float Y) {
pos = new PVector(X, Y);
}
void display() {
rectMode(CENTER);
noStroke();
fill(-1);
rect(pos.x, pos.y, 50, 50);
}
}
The problem is that the circles will only ever link to one of the squares, why is this happening and how can I fix it?