Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

5. All About Control > Checking Bounds

Checking Bounds

To make sure the PlayerSprite doesn’t go off the screen, you must implement bounds checking. Without it, the PlayerSprite will happily wander off the edge of the screen, never to be seen again.

Luckily, bounds checking is pretty easy. The PlayerSprite has a property called currentPosition that is used when rendering the sprite to the screen. To do the bounds checking, manual getters and setters are coded for the property. In the setter, if the sprite’s currentPosition value is less than zero or greater than the screen bounds, the sprite is restricted to either the left or right edge of the screen:

- (CGPoint)currentPosition {
    return currentPosition;
}
- (void)setCurrentPosition:(CGPoint)currentPos {
    currentPosition = currentPos;
    int screenWidth = [UIScreen mainScreen].bounds.size.width;
    if (currentPosition.x > screenWidth - self.width)
        currentPosition.x = screenWidth - self.width;
    else if (currentPosition.x <= 0)
        currentPosition.x = 0;
}


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial