Vectors and Vectorized Bouncing Ball

Processing provides a vector class. We can and will use it. However the best way to start learning vectors is to make your own class. I called ours BVector.

In class on Feb. 3rd we re-built the bouncing ball example using vectors. The vectorized version of Newton’s Laws is really quite elegant.

Vectorized Bouncing Ball

Source code for vectorized bouncing ball:

static final float DELTA_T = 0.1;
static final float GRAVITY = 0.5;

class BVector {
  
  float over;
  float down;
  
  BVector(float over, float down) {
    this.over = over;
    this.down = down;
  }
  
  void addWithScale(float scale, BVector otherVector) {
    this.over += scale * otherVector.over;
    this.down += scale * otherVector.down;
  }

}

// The acceleration of gravity points down
BVector gravity = new BVector(0.0, GRAVITY);

class Ball {

  BVector position;  
  BVector velocity;
  
  Ball() {
    position = new BVector(width/2.0, 0.0);
    velocity = new BVector(0.0, 0.0);
  }

  void display() {
    stroke(0);
    fill(0);
    ellipseMode(CENTER);
    ellipse(position.over, position.down, 5, 5);
  }

  void move() {
    // Gloriously simple vectorized version of Newton's Laws
    position.addWithScale(DELTA_T, velocity);
    velocity.addWithScale(DELTA_T, gravity);

    // The following takes care of hitting the floor
    if (position.down > height) {
      position.down = height;
      velocity.down *= -0.9;
    }
  }

}

Ball b;

void setup() {
  size(640, 360);
  b = new Ball();
  background(255);
}

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