Spot Borrows Bouncing Ball Behavior
// Lesson 11: Object Oriented Coding.
 
/*
  The class Spot now has an extra method 'move()' to give it a bouncing ball behavior
  And the addition of an extra Class property, the instance variable speed.
*/
 
Spot sp;
 
void setup() {
  size(100, 100);
  smooth();
  noStroke();
 
  sp = new Spot(33, 50, 30, 0.2); // creating new instance of spot, with speed as 4th argument
}
 
void draw() {
  background(0);
  sp.move();
  sp.display();
}
 
// ---------------------------
// Definition of the class Spot
 
class Spot {
  float x;
  float y;
  float diameter;
  float speed; // the float speed is needed for bouncing.
 
  // The constructor now has 4 arguments, to set the 4 parameters of a Spot
  Spot(float newX, float newY, float newDiameter, float newSpeed) {
    x = newX;
    y = newY;
    diameter = newDiameter;
    speed = newSpeed;
  }
 
  /*
  The new move() method:
  makes each Spot bounce up and down.
  */
  void move() {
    y = y + speed;
    if ((y < 0) || (y > height)) {
      speed = speed * -1;
    } 
  }
 
  void display() {
    ellipse(x, y, diameter, diameter);
  }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License