Jump to content
  • Advertisement
Sign in to follow this  
PeterVercauteren

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!