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 › An array of objects
Page Index Toggle Pages: 1
An array of objects? (Read 869 times)
An array of objects?
Apr 29th, 2010, 9:16am
 
I want to make a large number of instances of an object, such as ants.
How would I go about making this happen?

Allso, I think I might be posting in the wrong area.  Undecided
Re: An array of objects?
Reply #1 - Apr 29th, 2010, 9:53am
 
I suggest to use a for loop...
Re: An array of objects?
Reply #2 - Apr 29th, 2010, 10:20am
 
Yup, the for loop does the trick.
I also recommend looking into ArrayLists.
Makes it a breeze to add and remove objects.
Re: An array of objects?
Reply #3 - Apr 30th, 2010, 10:59am
 
Maybe an examples is helpful:
Quote:
ArrayList AntList;
myAnt A;
int maxAnts=10;

void setup()
{
  size(600,400);
  strokeWeight(5);
  stroke(255);
  AntList = new ArrayList();
  for (int i=0;i<maxAnts;i++)
      AntList.add( new myAnt( random(0,width),random(0,height) ) );
}
void draw()
{
  background(0);
  for (int i=0; i<AntList.size();i++)
   {
     A = (myAnt) AntList.get(i);
     A.pos.x += random(-5,5);
     A.pos.y += random(-5,5);
     A.Draw();
   }
}
class myAnt
{
  PVector pos;
  myAnt (float x,float y){pos=new PVector(x,y);}
  void Draw(){point(pos.x,pos.y);}
}

Re: An array of objects?
Reply #4 - Apr 30th, 2010, 1:21pm
 
Wonderful, thank you all for your input, and sorry for the superfluous posts. Cheesy
Page Index Toggle Pages: 1