In our last project, we learned how to move our dot on a single axis, but keep it from falling off the edge of the screen by setting and testing boundaries. In this project, we're going to start moving the dot on two axes (left and right; up and down) and learn how to constrain the dot on both axes so that it doesn't fall off the screen.
Here is the code we finished with from our last project:
Adding the same functionality along the other axis (the
y-axis) is actually pretty simple. In addition to changing
the x location by 1 each time through the loop, we also do the same
with the y location. This requires another direction
variable
to keep track of the y-axis direction:
And then we need to increment in the y-direction each time through the loop and test whether we've hit the y-axis edge:
To avoid confusion with the variable names, we'll also change the previous
variable direction
to x_direction
Lastly, you'll probably want to set the initial position of the ball to something other than (0, 0) to make the bouncing a little more interesting. In fact, you can play around with different initial points and see how it affects the bouncing.
Give it a try. You should now see the dot bouncing back and forth on the display in two directions.
Here is the final code: