1

Basically my game is to stop the rocks falling from the sky using a plank. I'm not sure what is not functioning correctly, but here is my code: In the RockManager class

public void CheckForPlankCollision(Plank plank)
{
    foreach (GameComponent component in Game.Components)
    {
        if (component is FallingRock rock)
        {
            if (plank.Bounds.Intersects(rock.Bounds))
            {
                rock.HandleCollision();
                Rectangle bounds = rock.Bounds;
            }
        }
    }
}

In the Rocks class

public void HandleCollision()
{
    //rockPosition = rockAfterImpactPosition; // I tried to move it offscreen
    //rockPosition = Vector2.Zero; //I tried for any reaction
    //this.Enabled = false; // tried this
    //Game.Components.Remove(this); //tried this
}

I'm also trying to implement a scoring system. (add 1 point if the rock hits the plank, subtract a point if it hits the ground)

fdrobidoux
  • 274
  • 4
  • 11
  • We will need more information to help you. You seem to be using a framework for managing your components and we would need to know which one. We probably also need more code since what you have added is not enough to understand correctly the situation. – abousquet Dec 08 '19 at 02:13
  • I prefer using a list of enemies (or rocks, in your case) and add the rocks to the rock list when visible on screen, and remove the rocks from the list when they need to be removed. – Steven Dec 09 '19 at 07:44
  • 1
    @abousquet He's not using anything fancy, this is all included in [vanilla MonoGame](https://learn.microsoft.com/en-us/previous-versions/windows/xna/bb195367(v=xnagamestudio.42)). – fdrobidoux Dec 10 '19 at 14:13
  • 1
    @fdrobidoux You're 100% right on this, my bad. – abousquet Dec 10 '19 at 15:02

1 Answers1

0

Try casting this as an IGameComponent or GameComponent object.

public void HandleCollision()
{
    Game.Components.Remove((GameComponent)this);
}

Tell me if this works for you !

EDIT: You might also want to defer the deletion of your game object to later, when it isn't used by the foreach (GameComponent component in Game.Components) loop, which might have a lock on removing elements during that time.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
fdrobidoux
  • 274
  • 4
  • 11
  • You're welcome. I'd kindly encourage you to mark my answer as the one that solved your question, since you mentioned so. – fdrobidoux Dec 17 '19 at 17:39