Bouncing Ball with Vectors

Bouncing Ball with Vectors by Daniel Shiffman.

Demonstration of using vectors to control motion of body This example is not object-oriented See AccelerationWithVectors for an example of how to simulate motion using vectors in an object

 
PVector location;  // Location of shape
PVector velocity;  // Velocity of shape
PVector gravity;   // Gravity acts at the shape's acceleration

void setup() {
  size(640,360);
  location = new PVector(100,100);
  velocity = new PVector(1.5,2.1);
  gravity = new PVector(0,0.2);

}

void draw() {
  background(0);
  
  // Add velocity to the location.
  location.add(velocity);
  // Add gravity to velocity
  velocity.add(gravity);
  
  // Bounce off edges
  if ((location.x > width) || (location.x < 0)) {
    velocity.x = velocity.x * -1;
  }
  if (location.y > height) {
    // We're reducing velocity ever so slightly 
    // when it hits the bottom of the window
    velocity.y = velocity.y * -0.95; 
    location.y = height;
  }

  // Display circle at location vector
  stroke(255);
  strokeWeight(2);
  fill(127);
  ellipse(location.x,location.y,48,48);
}


Functions Used

fill()

Sets the color used to fill shapes

Learn More
stroke()

Sets the color used to draw lines and borders around shapes

Learn More
size()

Defines the dimension of the display window width and height in units of pixels

Learn More
ellipse()

Draws an ellipse (oval) to the screen

Learn More
setup()

The setup() function is run once, when the program starts

Learn More
strokeWeight()

Sets the width of the stroke used for lines, points, and the border around shapes

Learn More
draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More
PVector

A class to describe a two or three dimensional vector, specifically a Euclidean (also known as geometric) vector

Learn More
background()

The background() function sets the color used for the background of the Processing window

Learn More