Keeping the Sprite in the Game Window

You have probably noticed that the rings sprite will disappear off the edge of the screen if you move it far enough. It's never a good idea to have the player controlling an object that is off-screen and unseen. To rectify this, update the position of the sprite at the end of the Update method. If the sprite has moved too far to the left or the right or too far up or down, correct its position to keep it in the game window. Add the following code at the end of the Update method, just before the call to base.Update:

if (ringsPosition.X < 0)
    ringsPosition.X = 0;
if (ringsPosition.Y < 0)
    ringsPosition.Y = 0;
if (ringsPosition.X > Window.ClientBounds.Width - ringsFrameSize.X)
    ringsPosition.X = Window.ClientBounds.Width - ringsFrameSize.X;
if (ringsPosition.Y > Window.ClientBounds.Height - ringsFrameSize.Y)
    ringsPosition.Y = Window.ClientBounds.Height - ringsFrameSize.Y;

Compile and run the game at this point, and you should be able to move the rings sprite around the screen just as before; however, it should always stay within the game window rather than disappearing off the edge of the screen.

Get Learning XNA 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.