Bounce Coding - Step 5 - If Statements

If this is your first time reading about Bounce Coding, I recommend you start from the beginning.

If statements

The last example animated our circle, but it moved right off the screen! To make it bounce off the edges of the screen we need to test whether the ball is on the edge of the screen. To do that we'll use an if statement. I've added a couple more variables to our program: velocity_x and screen_width.  The screen_width variable represents the width of the screen, which is 400 pixels. velocity_x is the speed that the circle will move in the x direction. A positive value will move the circle to the right, and a negative value will move it to the left. If we've hit the side of the screen, we can just multiply the velocity by -1 to flip it to the other direction. To check if we've hit the edge of the screen, we check if the right side of the circle is beyond the right edge of the screen or if the left side of the circle is beyond the left side of the screen. x-r is the x coordinate of the left side of the circle and x+r is the right side of the circle. 0 is the x coordinate of the left side of the screen and screen_width is the right side of the screen. We use || to perform the logical OR operation (did we hit the left side of the screen OR the right side of the screen). 

Things to note

  • Can you make it bounce in the y axis as well?
  • For more information on if statements, check out Khan Academy's tutorial.

 

Like free content like this? Consider donating to help support the creation of free, high quality content.