XNA book mistake?

Started by
0 comments, last by arthursouza 12 years, 7 months ago
Hi,

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
Advertisement
As far as I can see, the book is moving the sprite, then checking if it will pass the walls, if it is supposed to PASS the walls on this frame, he will act as if it had already bounced.

He moves the sprite in the beginning just to check if a collision is going to happen, then he moves the sprite back to where it was in the beginning. So, now that he already know if a collision will happen if he keeps moving forward, he can proceed with the movement, forwards, or bouncing the sprite.

Sorry if I wasnt able to explain properly, gotta use the rusty english a little more.

This topic is closed to new replies.

Advertisement