How can I randomly distribute circles without them overlapping? I've been banging my head against the wall!
I took info from these two sources:
and
I was trying to create my own from scratch while taking inspiration from these two sources. I feel like I'm close, but keep getting caught in infinite loop or null pointer exceptions (values don't get assigned).
Um, I'm probably over thinking this. Here's what I got so far.
- int circleCount = 10;
- float maxRadii = 200;
- float minRadii = 20;
- PVector circleArray[] = new PVector[circleCount];
- float radArray[] = new float[circleCount];
- PVector loc;
- float radii;
- void setup(){
- size(800, 600);
- background(0);
- initCircles();
- }
- void draw(){
- fill(150);
- noStroke();
- drawCircles();
- }
- void initCircles(){
- boolean overlap;
- boolean finalJ;
- for (int i = 0; i < circleCount; i ++){
- if (i < 2){ //added this because I kept getting caught in problems with i = 1 and j = 0, cancelling loop
- loc = new PVector(width/2 + (i * maxRadii), height/2 + (i * maxRadii));
- radii = ((minRadii + maxRadii - 2) /2);
- circleArray[i] = loc;
- radArray[i] = radii;
- println("inside initial i<2 loop, " + circleArray[i] + " circleArray[i] " + radArray[i] + " rads");
- overlap = false;
- }//end if i < 2
- else
- {
- overlap = true;
- for (int j = 0; j <= i; j ++){
- finalJ = false;
- if (j >= i - 1){
- finalJ = true;
- }//end else of if i < 2
- println("start j at " + j);
- println("comparing " + i + "i to " + j + "j " );
- while (overlap){
- println("start overlap");
- loc = new PVector(random(maxRadii, width - maxRadii), random(maxRadii, height - maxRadii));
- radii = random(minRadii, maxRadii);
- float rads = radii + radArray[j];
- float distance = loc.dist(circleArray[j]);
- println("comparing " + distance + " distance to " + radii + " radii");
- if (distance > rads && finalJ == false){
- println("no Overlap, more j to compare");
- break;
- }// end if distance > rads
- if (distance < rads)
- {
- println("overlap found to be true, back to overlap loop");
- overlap = true;
- }//end of if distance > rads
- while(finalJ){
- if(distance > rads){
- circleArray[i] = loc;
- radArray[i] = radii;
- overlap = false;
- finalJ = false;
- println("overlap found to be false at " + j + " j of " + i + ", assigning " + loc + " to circleArray " + i);
- }//end if distance > rads
- else//else of if under finalJ
- {
- overlap = true;
- }//end else
- }//end while(finalJ)
- } //end while (overlap)
- println("out of while overlap loop, iterating j");
- }//end for j
- println(" j compared to all existing i, incrementing i");
- }//end for i
- }//end else (of i)
- }//end initCircles
- void drawCircles(){
- for (int i = 0; i < circleCount; i ++){
- ellipse(circleArray[i].x, circleArray[i].y, radArray[i], radArray[i]);
- }
- }
/*
Please forgive my ignorance. I only know what I've already learned, and this world is a lot bigger than that.
*/
1