如何从Game.Components中删除GameComponent?

问题描述 投票:1回答:1

基本上,我的游戏是使用木板阻止岩石从天上掉下来。我不确定什么无法正常运行,但这是我的代码:在RockManager类中

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;
            }
        }
    }
}

在岩石班

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点)

xna sprite collision monogame
1个回答
0
投票

尝试将this强制转换为IGameComponentGameComponent对象。

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

告诉我,如果这对您有用!

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

© www.soinside.com 2019 - 2024. All rights reserved.