I'm reading the book "Learning XNA 4.0", and I'm in the object oriented design part. I'm having a weird problem with the collision of 2 rectangles.
I have a list of automateSprite and a Player class both derived from the class Sprite. In the update method I'm checking the play and the aotomatedSprite rectangles are touching each other, now when I got over the list I have a string called touching that represents the collision.
My problem is the veriable touching, only change if the player Sprite touch the last automateSprite in the list.
The code that the book offer for testing is to do Game.Exit()
if any collison was found.
That work on every automatedSprite in the list, but when I change it to my simple test, it acts like I only check the last item from a list of 4 automatedSprite.
here is the code:
string touching = "";
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
player.Update(gameTime, Game.Window.ClientBounds);
foreach (Sprite sprite in spriteList)
{
sprite.Update(gameTime, Game.Window.ClientBounds);
if (sprite.collisionRect.Intersects(player.collisionRect))
touching = "touching";
else
touching = "not touching";
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
spriteBatch.DrawString(font, touching, Vector2.Zero, Color.Red);
player.Draw(gameTime, spriteBatch);
foreach (Sprite sprite in spriteList)
{
sprite.Draw(gameTime, spriteBatch);
}
spriteBatch.End();
base.Draw(gameTime);
}
Edit-------------------------------------------------------------------------
solution:
I ask it in the game devlopment section and I got an answer.
I had to have a break;
in the foreach loop so it will not keep going after the it found a collison.