1
votes

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.

1

1 Answers

2
votes

It is because your code constantly overwrites the touching variable, so in the end only the last result is presented in it.

Before the foreach, reset the touching variable, with touching = ""; and extend the if like this:

if (sprite.collisionRect.Intersects(player.collisionRect) || touching == "touching")

This way you will get "touching" if any of the sprites are touching your players sprite.