Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Here we use vectors to simulate the effect of bouncing.  When the ball hits the edges of the canvas, it's vector is inverted in the appropriate axis, sending it back to where it came from.  

Code Block
PVector pos = new PVector(200,200);
PVector velocity = new PVector(1,0);
float damper = 0.99;

void setup() {
  size(600,600);
  fill(255);
}

void draw() {
  background(0);
 
  velocity.mult(damper); // always slow the ball down to simulate resistance 
  pos.add(velocity); // pos + velocity give us our new position! 
   
  // if the ball is above or below the screen, invert the y value of the velocity to send it back where it came from
  if (pos.y<0 || pos.y>height) {
    velocity.y = -velocity.y;
    pos.add(velocity);
  }
   // if the ball is left or right of the screen, invert the x value
  if (pos.x<0 || pos.x>width) {
    velocity.x = -velocity.x;
    pos.add(velocity);
  }
  ellipse(pos.x, pos.y,30,30);
  
  if(mousePressed) {
     // show us our "line of power"
     stroke(255,0,0);
     line(pos.x,pos.y, mouseX,mouseY);
     noStroke();
  }
};

void mouseReleased() {
    // when the mouse is released we give a ball a big push 
    PVector direction = new PVector(mouseX, mouseY);  
    direction.sub(pos);  // by subtracting the pos from mouse coordinates, we end up with a vectore between the two points
    direction.mult(.2);  // we shorten the magnitude to reduce the power of the push
    velocity.set(direction); //now we have our new velocity 
};

...