topical media & game development

talk show tell print

graphic-processing-learning-08-example-8-1-example-8-1.pde / pde



  // Learning Processing
  // Daniel Shiffman
  // http://www.learningprocessing.com
  
  // Example 8-1: A Car class and a Car object
  
  Car myCar; // Declare car object as a globle variable.
  
  void setup() {
    size(200,200);
    // Initialize Car object
    myCar = new Car(); // Initialize car object in setup() by calling constructor.
  }
  
  void draw() {
    background(255);
    // Operate Car object.
    myCar.move(); // Operate the car object in draw( ) by calling object methods using the dots syntax.
    myCar.display();
  }
  
  class Car { // Define a class below the rest of the program.
    color c; // Variables.
    float xpos;
    float ypos;
    float xspeed;
  
    Car() { // A constructor.
      c = color(175);
      xpos = width/2;
      ypos = height/2;
      xspeed = 1;
    }
  
    void display() { // Function.
      // The car is just a square
      rectMode(CENTER);
      stroke(0);
      fill(c);
      rect(xpos,ypos,20,10);
    }
  
    void move() { // Function.
      xpos = xpos + xspeed;
      if (xpos > width) {
        xpos = 0;
      }
    }
  }
  


(C) Æliens 20/2/2008

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.