Game Development Reference
The logic behind this is really simple, even though it looks like a bit of a rat's nest of code to read
through. All the code does is check to see whether the left, right, top, or bottom edges of the lh]uan
object are crossing the stage boundaries you set for them. It then forces the edges back if they've
gone over. To find out what the edges of the lh]uan object are, all you need to do is add or subtract
half the height or width of the lh]uan, depending on which edge you're checking for.
Let's take more detailed look at how this works with the first conditional statement:
This statement checks to see whether the right side of the lh]uan object is crossing the right side of
the stage. You know that the stage is 550 pixels wide. Let's pretend that at some point while moving
the lh]uan object around the screen, it has an t position of 530. If you add half its width, 25, to that
number, you end up with 555. 555 is a position that is definitely over the stage's right boundary, so the
directive inside the eb statement is triggered. That directive moves the lh]uan to a position that is the
same as the stage's maximum width (550) minus half of the lh]uan's width (25). That places it at a new
t position of 525. And because the lh]uan object has 25 pixels of “fat” around its middle, it looks as if
it has stopped exactly at the edge of the screen. Figure 6-10 illustrates how this works.
Figure 6-10. Precise screen boundaries using the object's half-width
The logic behind all the other conditional statements is exactly the same; only the values are different.
See if you can figure them out!