Public Group

# XNA book mistake?

This topic is 2642 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites
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.

1. 1
2. 2
Rutin
18
3. 3
khawk
15
4. 4
A4L
14
5. 5

• 10
• 13
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633745
• Total Posts
3013667
×