Easing and Twe­e­n­i­n­g - Bou­n­c­i­n­g Ball

by Travis Low
  • Show Sketch
/** @Peep sketch **/
 
/** @peep sketchcode */
float x; // Current x-coordinate
float y; // Current y-coordinate
float targetX; // Destination x-coordinate
float targetY; // Destination y-coordinate
float easing; // Size of each step along the path
boolean on = false;
 
void setup() {
  size(200, 200);
  background(0);
  noStroke();
  // Set the initial position
  x = random(10,190);
  y = random(10,190);
  // Set the final/target position
  targetX = random(x);
  targetY = random(y);
 
  // Adapt the position by 1% each update
  easing = 0.08;
}
 
void draw() {
  // Fade the background
  fill(0, 12);
  rect(0, 0, width, height);
  // If the current position is more than 1 pixel away from target  
  if (dist(x, y, targetX ++, targetY ++) > 1.0) {
    // Update the current position towards the target position
    x += (targetX - x) * easing;
    y += (targetY - y) * easing;
 
    if (targetX > width || targetY > height) {
      targetX = random(x);
      targetY = random(y);
    }
  }
  // Draw an ellipse at the current position
  fill(255);
  ellipse(x, y, 20, 20);
}

Comments

Nobody has said anything yet.