How do I have objects in an ArrayList collide with one another?

I'm trying to make a relatively simple little project for fun. In it, you can click your mouse to have a circle appear. That circle will grow until it collides with a wall or another circle, then shrink. You can keep clicking in different places to add new circles. Unfortunately, I can get everything but the circle-to-circle collision to work.

Here is my code:

ArrayList<Circle> circleArray = new ArrayList<Circle>();
int circleCount = 0;

void setup()
{
  size(300, 300);
}

void draw()
{
  background(0);

  for (int i = 0; i < circleCount; i++)
  {
    circleArray.get(i).display();
    circleArray.get(i).update();
    circleArray.get(i).collideWall();

    //for (int j = i+1; j < circleCount; j++)
    //{
    //  circleArray.get(i).collideCircle(circleArray.get(i));
    //}
  }
}


class Circle
{
  int x, y;
  int circumference;
  int radius;
  int growSpeed;
  boolean isGrowing;
  color col;

  Circle(int tempX, int tempY)
  {
    x = tempX;
    y = tempY;

    circumference = 10;
    radius = circumference/2;
    growSpeed = 1;
    isGrowing = true;
    col = color(random(100, 255), random(100, 255), random(100, 255));
  }

  void display()
  {
    // Draw circle:
    noStroke();
    fill(col);
    ellipse(x, y, circumference, circumference);
  }

  void update()
  {
    // Alternate growing and shrinking:
    if (isGrowing)
      circumference += growSpeed;
    else
      circumference -= growSpeed;

    // Redefine radius:
    radius = circumference/2;
  }

  void collideWall()
  {
    // Wall collision detection:
    if (radius > dist(x, y, x, 0) || radius > dist(x, y, x, height)
     || radius > dist(x, y, 0, y) || radius > dist(x, y, width, y))
      isGrowing = false;
    else if (circumference < 20)
      isGrowing = true;
  }

  void collideCircle(Circle other)
  {
    // Other circle collision detection:
    if (radius + other.radius > dist(x, y, other.x, other.y))
      isGrowing = false;
    else if (circumference < 20)
      isGrowing = true;
  }
}


void mouseClicked()
{
  circleArray.add(new Circle(mouseX, mouseY));
  circleCount++;
}
Tagged:

Answers

Sign In or Register to comment.