ArrayList interaction only recognizing one instance

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?

1 Like

Each Ball only remembers one nearest Square to connect to with a line. It (the Ball) is either connected to a singular Square, or it isn’t.

Balls don’t have multiple connections to many squares because they only have one Square they are ever connected to!

… What you need is for each Ball to remember which Balls it is connected to. The easiest way to do this would be to have an array of booleans in the Ball class so each Ball has a record if that Ball is connected to the i’th Square.

2 Likes

you can also have an ArrayList “nearest” in the Ball class with all the squares that are near at the moment

for loop over the ArrayList in display() in the Ball class

clear the ArrayList and fill it again very time in update in the Ball class

I got it running now

2 Likes

delete connected = false;

1 Like