Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm reading the book "Learining XNA 4.0", and I'm in the object oriented disgn 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 im checking if player and the aotomatedSprite rectangles are touching each other, now when I go over the list I have a string called touching that represent the collision.

My problem is the variable touching only changes if the player Sprite touches the last automateSprite in the list.

The code that the book offers for testing is to do Game.Exit() if any collision 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);
}

(sorry for my English)

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Even if a collision is detected, you continue to iterate through your list of sprite. This way, your variable touching will be set to "touching" only if your player collides with your last sprite.

Put a break to exit your loop when a collision occurs, like this

foreach (Sprite sprite in spriteList)
{
    sprite.Update(gameTime, Game.Window.ClientBounds);
    if (sprite.collisionRect.Intersects(player.collisionRect))
    {
        touching = "touching";
        break;
    }
    else
        touching = "not touching";
}
share|improve this answer
    
thank you now i understand the problem :) –  samy Apr 29 '12 at 14:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.