Monogame children 更新方法滞后

Monogame children update method lag

所以我是计算机编程的新手,但我了解 C# 的基础知识。

我正在做一个 Monogame 项目,并且正在为我的精灵制作一个更新方法。由于我的精灵是基于泰拉瑞亚的(我的意思是每个精灵都是不同的 body 部分)我制作了一个 children 列表。在该列表中,我放置了所有 body 精灵,并将列表附加到 parent(玩家的中心精灵)。

这是我的基本精灵更新方法:(不仅针对玩家)

public virtual void Update(GameTime gameTime, Rectangle clientBounds)
{
    timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;

    if (timeSinceLastFrame > millisecondsPerFrame)
    {
        timeSinceLastFrame = 0;
        ++currentFrame.X;

        if (currentFrame.X >= sheetSize.X)
        {
            currentFrame.X = 0;
            ++currentFrame.Y;

            if (currentFrame.Y >= sheetSize.Y)
            {
                currentFrame.Y = 0;
            }
        }
    }
}

这是我在另一个class:

中更新玩家精灵的方法
public override void Update(GameTime gameTime, Rectangle clientBounds)
{
    position += direction;

    // If sprite moves off screen
    if (position.X < 0)
    {
        position.X = 0;
    }

    if (position.Y < 0)
    {
        position.Y = 0;
    }

    if (position.X > clientBounds.Width - frameSize.X)
    {
        position.X = clientBounds.Width - frameSize.X;
    }

    if (position.Y > clientBounds.Height - frameSize.Y)
    {
        position.Y = clientBounds.Height - frameSize.Y;
    } 

    // Continue base update method 
    base.Update(gameTime, clientBounds);
}

这是绘图方法,效果很好:

public override void Draw(GameTime gameTime)
{
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise);
    player.Draw(gameTime, spriteBatch);
    player.children.ForEach(c => c.Draw(gameTime, spriteBatch));
    spriteBatch.End();

    base.Draw(gameTime);
}

但更新方法滞后:

public override void Update(GameTime gameTime)
{
    player.children.Add(playerDeux);
    float millisecondsRunning = 30;
    float millisecondsWalking = millisecondsRunning  * 2f;

    if (player.running == true)
    {
        player.millisecondsPerFrame = millisecondsRunning;
    }

    else if (player.running == false)
    {
        player.millisecondsPerFrame = 65;
        playerDeux.millisecondsPerFrame = 30;
    }

    if (player.walking == false)
    {
        player.textureImage = Game.Content.Load<Texture2D>(@"Images/" + s1[1]);
    }

    player.Update(gameTime, Game.Window.ClientBounds);
    player.children.ForEach(c => c.Update(gameTime, Game.Window.ClientBounds));
    base.Update(gameTime);
}

所以当我在所有 children 上调用 draw 方法时它工作得很好,但是当我在 children 上调用 Update 方法时它非常滞后并且程序甚至停止工作。

有更好的方法吗?

编辑:另请注意,此 class 尚未完成,这只是我绘制 2 个精灵并更新(动画播放)它们的测试。 + player.textureImage中的s1[1] = Game.Content.Load(@"Images/" + s1[1]);只是数组中的字符串名称。

您的代码有些奇怪,但我认为罪魁祸首是 player.children.Add(playerDeux)。现在的方式是,您在每次更新时将 playerDeux 添加到子列表,然后每次更新 playerDeux 一次 Update 已经 运行。看起来您想将这行代码移动到您的 InitializeLoadContent 方法中。

此外,您应该只在 LoadContent 方法中加载纹理一次,并且只在 Update 方法中引用内存中的纹理。这不是游戏如此缓慢的主要原因,但这是不必要的开销。