the basic idea could be to make a set of random data
like for a rectangle x,y,w,h
and before you add that rect to the arraylist
check if it would collide with any already existing rects.
( and as long that is the case make a new set ( to test with ) )
and for that collision check see
proof of concept:
// array list of class
class MyRect {
int x, y, w, h;
color rf = color(0, 200, 0);
color rs = color(0, 0, 200);
MyRect(int x, int y, int w, int h) {
this.x=x;
this.y=y;
this.w=w;
this.h=h;
}
void draw() {
push();
fill(rf);
stroke(rs);
rect(x, y, w, h);
pop();
}
}
ArrayList<MyRect> myrects = new ArrayList<MyRect>();
int x, y, w, h;
int many =10;
boolean avoid_collide = true; //false;
void random_set() {
// random rects
w = int(random(10, 30));
h = int(random(10, 30));
x = int(random(0, width-w));
y = int(random(0, height-h));
}
void make_myrects() {
myrects = new ArrayList<MyRect>(); // reset
for (int i=0; i<many; i++) {
random_set(); // init random rect settings
if ( avoid_collide ) while ( collide(x, y, w, h) ) random_set(); // try again until not collide with existing
myrects.add(new MyRect(x, y, w, h)); // ok, make it
println("i "+i+" x "+x+" y "+y+" w "+w+" h "+h);
}
}
// RECTANGLE/RECTANGLE // http://www.jeffreythompson.org/collision-detection/rect-rect.php
boolean collide(float r1x, float r1y, float r1w, float r1h) { // new random rect to test before we make it!!
if ( myrects.size() > 0) { // check on all existing rects if that NEW ONE would collide
for ( MyRect onerect : myrects) {
if (r1x + r1w >= onerect.x && // r1 right edge past r2 left
r1x <= onerect.x + onerect.w && // r1 left edge past r2 right
r1y + r1h >= onerect.y && // r1 top edge past r2 bottom
r1y <= onerect.y + onerect.h) // r1 bottom edge past r2 top
return true;
}
}
return false;
}
void show_myrects() {
for ( MyRect onerect : myrects) onerect.draw();
}
void setup() {
size(200, 200);
make_myrects();
println("array size: "+myrects.size());
}
void draw() {
background(200, 200, 0);
show_myrects();
}
void mousePressed() {
make_myrects();
}