Bouncing Ball With Friction
// Bouncing ball which you can drag to animate
 
// Declaring the variables
float posX; // position variables
float posY;
 
float speedX; // speed variables
float speedY;
 
void setup()
{
  // Setting up the window size and drawing conditions
  size(200,200);
  smooth();
 
  // Initializing the variables
  posX = width / 2;
  posY = width / 2;
  speedX = 0;
  speedY = 0;
}
 
void draw()
{
  // If the mouse is pressed within the ball, use the mouse speed
  if (mousePressed) {
    if ((mouseX > (posX - 10) && mouseX < (posX + 10)) &&
        (mouseY > (posY - 10) && mouseY < (posY + 10))) { 
      speedX = mouseX - pmouseX;
      speedY = mouseY - pmouseY;
    }
  }
 
  // Calculate the new position
  posX = posX + speedX;
  posY = posY + speedY;
 
  // If the position is outside of the window: bounce
  if (posX > width - 10 || posX < 10) {
    speedX = -speedX;
  }
  if (posY > height - 10 || posY < 10) {
    speedY = -speedY;
  }
  // Add a little friction
  speedX = speedX * 0.995;
  speedY = speedY * 0.995;
 
  // Draw the actual ball
  background(100);
  ellipse(posX, posY, 20, 20);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License