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 › Multiple objects
Page Index Toggle Pages: 1
Multiple objects (Read 396 times)
Multiple objects
May 31st, 2009, 10:46am
 
Hello all,

I have been working through this tutorial on OOP http://processing.org/learning/objects/

and have found it really clear and useful. Nice one. I wondered if somebody could enlighten me on the following...

How do I go about creating multiple instances of an object using an array and for loop? For example, in the tutorial above two objects are declared and then initalised:

Car myCar1;
Car myCar2; // Two objects!

Say I wanted to declare and initalise 200 objects, what is the most efficient way to do this (other than declaring Car myCar3, Car myCar4  etc... all the way to Car myCar200)? I have tried setting up an array and looping through but I am kicking up all sorts of errors. Any help would be really appreciated.

thanks



Re: Multiple objects
Reply #1 - May 31st, 2009, 11:44am
 
hello,
first of all you would have to declare the array...
something like that:

Car[] carArray = new Car[200];
//and then to initialize like that
for(int i = 0;i < 200;i++){
   carArray[i] = new Car();
}


there are some things you might want to consider like what will go where and if you want to make it global of have it in a function
but this is basically the idea...
hope it helps
Re: Multiple objects
Reply #2 - Jun 1st, 2009, 12:47pm
 
ahhh. Thanks. I had another bash with this code here:

int numCar = 6;
// Declare and create array
Car[] cars = new Car[numCar];

//Car myCar1;
//Car myCar2; // Two objects!

void setup() {
 size(200,200);
 // Parameters go inside the parentheses when the object is constructed.
 for(int i = 0; i <cars.length; i++){
   cars[i] = new Car(color(255,0,0),0,i*10,2);
 }
}

void draw() {
 background(255);
 for(int i = 0; i <cars.length; i++){
   cars[i].move();
   cars[i].display();
 }
}

// Even though there are multiple objects, we still only need one class.
// No matter how many cookies we make, only one cookie cutter is needed.
class Car {
 color c;
 float xpos;
 float ypos;
 float xspeed;

 // The Constructor is defined with arguments.
 Car(color tempC, float tempXpos, float tempYpos, float tempXspeed) {
   c = tempC;
   xpos = tempXpos;
   ypos = tempYpos;
   xspeed = tempXspeed;
 }

 void display() {
   stroke(0);
   fill(c);
   rectMode(CENTER);
   rect(xpos,ypos,20,10);
 }

 void move() {
   xpos = xpos + xspeed;
   if (xpos > width) {
     xpos = 0;
   }
 }
}

it seems to work ok. Thanks again for the suggestion.


Page Index Toggle Pages: 1