2
votes

I've been trying keep a sprite from leaving the screen so far I keep it from leaving the left side of screen and the bottom of the screen. But when I try keep it from leaving the right side of the screen. It's does show the sprite/character.

if (charpos.X <= 0)
    charpos.X = 0;
else
if (charpos.X <= 1280)
    charpos.X = 1280;

When I have on if(charpos.X <= 1280) charpos.X = 1280; It teleports the sprite somewhere else, that I cannot see. Am I coding the right side of the screen wrong?

2

2 Answers

2
votes

Yes, you coded it wrong. You meant >= 1280. The <= will always evaluate to true in a normal game situation and set the X position to 1280.

Since XNA coordinates draw from the top-left corner, you can't see that position (on a window 1280 wide). You actually want:

int rightSide = 1280 - sprite.Width;
if (charpos.X > rightSide )
    charpos.X = rightSide ;

To subtract the sprites width from the edge, allowing the sprite to always remain "on-screen". The "or equals" part of the comparison is not necessary, since an equals condition would just set the value to what it already is.

1
votes

You have one definite and one possible error in your code.

The definite error is your second if statement:

if (charpos.x <= 1280)

That should be:

if (charpos.x >= 1280)

Otherwise, anything on screen will be considered off screen.

The possible error is in how you are moving the sprite back on screen. If your sprite origin for position purposes is at the upper left corner of the sprite, setting the x-coordinate to 1280 will position the sprite just off the right side of the screen.

To fix that, you'll want to change your code to something like this:

charpos.x = 1280 - character.width;

That will account for the width of the character when keeping it on screen.