Game Programming: Coding for Fun 239
is picx + picw/2, to be less than or equal to the top-right corner of
the paddle, whose x-coordinate is paddlex + paddlew (or the starting
x-coordinate of the paddle plus the paddle’s width). In code, this
would be picx + picw/2 <= paddlex + paddlew.
We can put these two together into a single if statement,
but that’s not quite enough. Those x-coordinates cover the whole
screen from the left corner of the paddle to the right corner, from
the top of the screen to the bottom. With just the x-coordinates
determined, our ball could be anywhere in the y direction, so
we need to narrow that down. It’s not enough to know that our
ball is within the horizontal limits of the paddle; we also have
to know that our ball is within the vertical range of y-coordinate
values that could allow it to collide with the paddle.
We know that the top of our paddle is located at 550 pixels in
the y direction, near the bottom of the screen, because our setup
includes the line paddley = 550 and the rectangle begins at that
y-coordinate and continues down for 25 pixels, our paddle’s height
stored in paddleh. We know our picture is 100 pixels tall, so let’s
store that as a variable, pich (for picture height), that we can add to
our setup section: pich = 100.
For our ball’s y-coordinate to hit the paddle, the picy loca-
tion plus the picture’s height, pich, needs to be at least paddley or
greater for the bottom of the picture (picy + pich) to touch the top
of the paddle (paddley). Part of our if statement for the ball hitting
the paddle in the y direction would be if picy + pich >= paddley. But
this condition alone would allow the ball to be anywhere greater
than paddley, even at the bottom edge of the screen. We don’t want
the user to be able to get points for moving the paddle into the
ball after the ball has hit the bottom edge, so we need another
if condition that sets the maximum y-coordinate value we’ll give
points for.
A natural choice for the maximum
y-coordinate value for earning a point might be
the bottom of the paddle, or paddley + paddleh
(the paddle’s y-coordinate, plus its height). But
if the bottom of our ball is past the bottom of
the paddle, the player shouldn’t get a point for
hitting the ball, so we want picy + pich (the
bottom of the ball) to be less than or equal to
paddley + paddleh—in other words, picy + pich
<= paddley + paddleh.