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 & HelpSyntax Questions › Instantiating Objects in Draw
Page Index Toggle Pages: 1
Instantiating Objects in Draw (Read 341 times)
Instantiating Objects in Draw
Mar 12th, 2008, 12:03am
 
Hi, I am trying to instantiate objects in draw() so that I can add more or less of the objects in real-time (pressing 'up' or 'down').  Whenever I add a new object, I want it to be placed in a random x,y coord in the screen and stay still.  The problem is when I run the sketch the object can't seem to keep their x, y locations.  Any help would be appreciated!

Code:

int numObj = 10;
Objects[]obj = new Objects[numObj];

void setup(){
background(255);
size(800, 800);

}

void draw(){
background(255);
placeObj();
}

void placeObj(){
for(int i = 0; i < numObj; i++){
obj[i] = new Objects();
obj[i].display();
}
}

void keyPressed(){
if(key == CODED){
if(keyCode == UP){
numObj++;
obj = new Objects[numObj];
}
if(keyCode == DOWN){
numObj--;
if(numObj < 1){
numObj = 0;
}
obj = new Objects[numObj];

}
}
}

class Objects{
float x, y;
boolean drawn;


void display(){
if(drawn != true){
chooseRndLoc();
}
noFill();
smooth();
pushMatrix();
translate(x, y);
ellipse(0,0,20,20);
drawn = true;
popMatrix();
}
void chooseRndLoc(){
if(drawn != true){
float rndX = random(20, width -20);
float rndY = random(20, height - 20);
x = rndX;
y = rndY;
}
}
}

Re: Instantiating Objects in Draw
Reply #1 - Mar 12th, 2008, 1:14pm
 
draw() calls placeObj() every loop. placeObj() creates numObjs NEW objects *every time*. they aren't losing their x,y locations, they are different objects every time.

use an arraylist rather than an array - easier to resize

initialise the start array in setup, not in the draw loop

change keyPressed to create *one* new Object and add it to the arraylist using add()

(and stop calling your Objects Objects - Object is a reserve word and it's confusing) 8)
Re: Instantiating Objects in Draw
Reply #2 - Mar 14th, 2008, 3:07am
 
Hey thanks for the reply.  I'll try the arraylist... haven't played with it much, but I hear good things about it.  So, here I go.
Re: Instantiating Objects in Draw
Reply #3 - Mar 14th, 2008, 4:10am
 
works like a charm~
Page Index Toggle Pages: 1