Code

float px;
float py;
float vx;
float vy;

void setup(){
  smooth();
  size(300,300);
  reset();
}

void draw(){
  background(0);
  edge();
  puck();

}
void mousePressed(){
  reset();
}

void puck(){
  ellipse(px=px+vx, py=py+vy, 20,20);
}
void reset(){
  px=150;
  py=150;
  vx=random(-4,4);
  vy=random(-4,4);
}

void edge(){
 if ((px<0)|| (px>width)){
  vx=-vx; 
 }
 if ((py<0)|| (py>height)){
  vy=-vy; 
 }
}

0403 - Pong II: Towards a simple game

Statement:Modify your previous exercise (0402) so that the puck bounces off the edges of the canvas. To achieve the bouncing effect, implement the following tests, such that they execute on every frame of animation:

  • If the x-position (px) is greater than the width of the canvas, flip the sign of the x-velocity (vx). (There are several ways of flipping the sign of a number, such as multiplying it by -1, or subtracting it from 0.)
  • If px is less than 0, flip the sign of vx.
  • If py is greater than the height of the canvas, flip the sign of vy.
  • If py is less than 0, flip the sign of vy.

    hide statement