Motion: Bounce

Model velocity and edge reflection for lively motion.

Example 1: Single Ball Bounce

Code

let x = 200;
let y = 200;
let vx = 3;
let vy = 2.5;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(250);
  x += vx;
  y += vy;

  if (x < 20 || x > width - 20) vx *= -1;
  if (y < 20 || y > height - 20) vy *= -1;

  fill(255, 48, 145);
  noStroke();
  circle(x, y, 40);
}

Try this: Dampen velocity a little each bounce to simulate friction.

Open sketch in new tab

Example 2: Gravity Bounce

Code

let y = 60;
let vy = 0;
const g = 0.4;
const rest = -0.82;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(255);
  vy += g;
  y += vy;

  if (y > height - 30) {
    y = height - 30;
    vy *= rest;
  }

  fill(255, 44, 140);
  noStroke();
  circle(width / 2, y, 60);
}

Try this: Adjust restitution to compare “rubber” vs “heavy” bounce.

Open sketch in new tab

Resources