Example

Car

// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 9-9: An array of Car objects

Car[] cars = new Car[100]; // An array of 100 Car objects!

void setup() {
  size(200,200);
  smooth();
  for (int i = 0; i < cars.length; i ++ ) { // Initialize each Car using a for loop.
    cars[i] = new Car(color(i*2),0,i*2,i/20.0); 
  }
}

void draw() {
  background(255);
  for (int i = 0; i < cars.length; i ++ ) { // Run each Car using a for loop.
    cars[i].move();
    cars[i].display();
  }
}
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 9-9: An array of Car objects


// The Car class does not change whether we are making one car, 100 cars or 1,000 cars!
class Car { 
  color c;
  float xpos;
  float ypos;
  float xspeed;

  Car(color c_, float xpos_, float ypos_, float xspeed_) {
    c = c_;
    xpos = xpos_;
    ypos = ypos_;
    xspeed = xspeed_;
  }

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

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

    What does “_” mean with regards to the code?

  • http://www.learningprocessing.com Daniel Shiffman

    It doesn’t mean anything. It’s just a programmer’s convention to use an underscore when a variable coming in as an argument is assigned to a variable within the class. You could just as easily write:

     Car(color tempC) {
        c = tempC;
      }
    

    or

     Car(color asdfasdfwe) {
        c = asdfasdfwe;
      }
    
  • http://www.facebook.com/piero.barbagelata Piero Barbagelata

    Why did you put the for loop in the setup method?

  • Anonymous

    That for loop is used to initialize all the car objects.  

  • Basheersubei

    Thank you for the wonderful example!

  • Maryam

    When I try and load this code, I get an error “The Constructor classEg.Car(int,int,int,float) is undefined”. in relation to this line of code–>
    for (int i = 0; i < cars.length; i ++ ) { // Initialize each Car using a for loop.
    cars[i] = new Car(color(i*2),0,i*2,i/20.0);
    … how come it won't work in my processing?

  • shiffman

    Did you retype it? Perhaps you missed something. I am not getting this error.

    http://www.learningprocessing.com/example-files/chapter09/zip/example_9_9.zip

  • marmota peluda

    señor porque?