We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › 2D array for simple problem
Page Index Toggle Pages: 1
2D array for simple problem (Read 360 times)
2D array for simple problem
Mar 13th, 2009, 2:46am
 
Dudes.

Ive got a problem with this simple sketch that im trying to write. I have a size(400,400)and within that i have a rect(100,100,200,200) and I want to draw 20 random 50,20 rects with 2 conditions
they can not overlap the big rect in the middle and they cant overlap each other.
I managed the first task but cant figure out the second one. any help is greatly appreciated.

int x = 50;
int y = 20;
float[] xa = new float [20];
float[] ya = new float [20];
int timer = 0;
float d = 0;
void setup(){
 background(0);
 size(400,400);
 smooth();
 noFill();
 stroke(255);
 rect(100,100,200,200);

}

void draw(){
 
 float xpos = random(350);
 float ypos = random(380);
if (timer < 19){
 if (xpos + x > 100 && xpos < 300  && ypos + y > 100 && ypos < 300){
xpos = 0;
ypos = 0;
   }
   
   println(timer);
   timer = timer + 1;
   xa[timer] = xpos;
   ya[timer] = ypos;
   println(xa[timer]);
d = dist(xpos, ypos, xa[timer -1], ya[timer - 1]);
println("d =" + d);
if (xa[timer] <= 0 || ya[timer] <= 0){
  timer = timer - 1;


}else{
 rect(xpos,ypos,x,y);
 PFont font;
   font = loadFont("Helvetica-Bold-16.vlw");
   textFont(font);
 
 text(timer, xpos, ypos);
 
}
}
 }
 

Re: 2D array for simple problem
Reply #1 - Mar 13th, 2009, 1:37pm
 
You have to do the intersection test on each previously drawn square. You were on the right track.
Code:
int w = 50;
int h = 20;
float[] xa = new float [20];
float[] ya = new float [20];
int timer = 0;

void setup(){
background(0);
size(400,400);
smooth();
noFill();
stroke(255);
rect(100,100,200,200);

// Put that outside of drawing loop!
PFont font;
font = loadFont("Helvetica-Bold-16.vlw");
textFont(font);
}

void draw(){

if (timer == 19) {
noLoop(); // Stop drawing
return;
}
float xpos = random(350);
float ypos = random(380);
if (xpos + w > 100 && xpos < 300 && ypos + h > 100 && ypos < 300){
// Reject rects inside big square
return;
}
for (int i = 0; i <= timer; i++)
{
if (Intersects(xpos, ypos, xa[i], ya[i]))
{
return; // Try again
}
}

println(timer);
timer++;
xa[timer] = xpos;
ya[timer] = ypos;

rect(xpos, ypos,w, h);
text(timer, xpos, ypos);
}

boolean Intersects(float x1, float y1, float x2, float y2)
{
return x1 + w > x2 && x1 < x2 + w &&
y1 + h > y2 && y1 < y2 + h;
}
Re: 2D array for simple problem
Reply #2 - Mar 13th, 2009, 2:03pm
 
Thanks alot friend. I was making thing a little too complicated.

Cheers

Page Index Toggle Pages: 1