So I recently borrowed a book called "XNA Game Studio 4.0 Programming"
Now for those who have this book, the passage I'll be talking about is page 37.
Here it explains how to move a sprite (continuously) around; when the sprite hits the borders it will bounce of.
Now this is the code it uses:
position += (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
if (!GraphicsDevice.Viewport.Bounds.Contains(new Rectangle(
(int)position.X, (int)position.Y, texture.Width, texture.Height)))
{
bool negateX = false;
bool negateY = false;
// check if hits left or right wall
if ((position.X < 0) || ((position.X + texture.Width) >
GraphicsDevice.Viewport.Width))
{
negateX = true;
}
// check if hits top or bottom wall
if ((position.Y < 0) || ((position.Y + texture.Height) >
GraphicsDevice.Viewport.Height))
{
negateY = true;
}
// move back to where you were before
position -= (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
if (negateX) velocity.X *= -1;
if (negateY) velocity.Y *= -1;
position += (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
}
Now, I get the meaning of the code... except for
// move back to where you were before
position -= (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
Why would this be needed?
Regards