Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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;
}