In our previous project, we learned how to move a dot on a single axis (left to right), and how to keep it from falling off the edge of the screen by setting and testing boundaries.
In this project, we're going to learn to move the dot on two axes (left and right, as well as up and down) and learn how to constrain the dot on both axes so that it doesn't fall off the screen.
Your breadboard should still have the circuit we wired in the project. As a reminder, here is what it should look like:
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. To avoid confusion with the variable names, we'll also change the
previous variable direction
to x_direction
In addition, we need to increment in the y-direction each time through the loop and test whether we've hit the y-axis edge.
Here is the final code, with the new code marked with arrows:
Give it a try. You should now see the dot moving on the display in two directions simultaneously.
Set the initial position of the ball to something other than (0, 0) to make the bouncing a little more interesting. Can you get it to bounce in a diamond shape?
As is, the ball moves the same distance in both the x and y directions each time it is moved. Can you increase the distance the ball moves in one of the directions each time it's moved.
Using one of the random
functions, can you add a little
randomness to the ball's position (perhaps move it a random distance each
time it's moved) to make the ball wiggle about the display?