Search code examples
c#xnaspritecollision

XNA Sprite only Disappears when player intersects


I am making a game where a player will go around collecting kiwis. When the player touches a kiwi, I want the kiwi sprite to disappear permanently. So far, I can only make the kiwi sprite disappear while the player is touching them, and when the player moves off the kiwi rectangle, the kiwi sprite reappears.

Here is the intersect function I created in the Kiwi class:

public void Intersect(Rectangle playerRect, SpriteBatch spriteBatch)
    {
        foreach (Rectangle kiwiRect in kiwiRectangle)
        {
            if (!kiwiRect.Intersects(playerRect))
            {
                isCollected = false;
            }
            else
                isCollected = true;

            if (!isCollected)
            {
                spriteBatch.Draw(kiwiTexture, kiwiRect, Color.White);
            }
        }
    }

And then I put this function in the Draw function in the main game class.

    protected override void Draw(GameTime gameTime)
    {

         GraphicsDevice.Clear(Color.CornflowerBlue);
         spriteBatch.Begin();

         if (gameState == GameState.Playing)
         {


             GraphicsDevice.Clear(Color.Green);




             kiwiClass.Intersect(Sprite.spriteDestinationRectangle, spriteBatch);


             Sprite.Draw(spriteBatch);


         }



         spriteBatch.End();


         base.Draw(gameTime);
      }

Solution

  • You should only check if there's an intersection until there is one. You don't ever want to do isCollected = false or else the kiwi will reappear.

    Your Intersect() method should look like this:

    public void Intersect(Rectangle rectangle, SpriteBatch spriteBatch)
    {
        foreach (Rectangle kiwiRect in kiwiRectangle)
        {
            if (!isCollected)
            {
                if (kiwiRect.Intersects(playerRect))
                {
                    isCollected = true;
                }
            }
    
            if (!isCollected)
            {
                spriteBatch.Draw(kiwiTexture, kiwiRect, Color.White);
            }
        }
    }
    

    EDIT: Actually, you need to keep track of each kiwi's collected status individually. You can change isCollected to a list instead:

    List<Rectangle> collectedKiwis = new List<Rectangle>();
    

    And then change the Intersect() method to this:

    public void Intersect(Rectangle rectangle, SpriteBatch spriteBatch)
    {
        foreach (Rectangle kiwiRect in kiwiRectangle.Except(collectedKiwis))
        {
            if (kiwiRect.Intersects(playerRect))
            {
                collectedKiwis.Add(kiwiRect);
            }
            else
            {
                spriteBatch.Draw(kiwiTexture, kiwiRect, Color.White);
            }
        }
    }