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

// Example 8-2: Two Car objects

Car myCar1;
Car myCar2; // Two objects!

void setup() {
  size(200,200);
  myCar1 = new Car(color(255,0,0),0,100,2); // Parameters go inside the parentheses when the object is constructed.
  myCar2 = new Car(color(0,0,255),0,10,1);
}

void draw() {
  background(255);
  myCar1.move();
  myCar1.display();
  myCar2.move();
  myCar2.display();
}

class Car { // 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.Isn’t object-oriented programming swell?
  color c;
  float xpos;
  float ypos;
  float xspeed;

  Car(color tempC, float tempXpos, float tempYpos, float tempXspeed) { // The Constructor is defined with arguments.
    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;
    }
  }
}

2 Comments

»

  1. how can i create multiple objects with a for loop? multiple cars…

    thanks

    Comment by david — March 13, 2010 @ 11:15 pm

  2. Take a look at this example:

    http://www.learningprocessing.com/examples/chapter-9/example-9-9/

    Comment by Daniel Shiffman — March 15, 2010 @ 10:01 am

Leave a comment