如何从 Game.Components 中删除 GameComponent?

How do I delete a GameComponent from Game.Components?

基本上我的游戏是用木板阻止从天上掉下来的石头。 我不确定什么功能不正常,但这是我的代码: 在 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;
            }
        }
    }
}

在岩石区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
}

我也在尝试实施评分系统。 (石头打在木板上加1分,打在地上减1分)

尝试将 this 转换为 IGameComponentGameComponent 对象。

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

告诉我这是否适合你!

编辑:您可能还想将游戏对象的删除推迟到以后,当 foreach (GameComponent component in Game.Components) 循环不使用它时,这可能会锁定在此期间删除元素。