使用 for 循环 xna 4.0 绘制多个精灵

Drawing multiple sprites with a for loop xna 4.0

我目前正在开发一款平台游戏,我想在一个屏幕状态下绘制 40 个项目,但我不想对它们全部进行硬编码。到目前为止,这是我尝试过的方法:

雪碧class:

       class Sprite
{
    //texture, position and color
    public Texture2D texture;
    public Vector2 position;
    public Color color;
}

定义:

Sprite levelboxbg;
int LevelBoxX = 20;

正在加载:

        levelboxbg = new Sprite();
        levelboxbg.texture = Content.Load<Texture2D>("LevelBoxBeta");
        levelboxbg.position = new Vector2(0, 0);
        levelboxbg.color = Color.White;

执行:

     public void DrawLevelBoxes(SpriteBatch spriteBatch)
    {
        for (int i = 0; i < 10; i++)
        {
            spriteBatch.Draw(levelboxbg.texture, new Vector2(LevelBoxX + 20 ,0), levelboxbg.color);
            LevelBoxX += 20;
        }
    }

然后我在绘图函数中调用该方法。

Visual studio 给了我 0 个错误,它会 运行;然而,当我到达它应该绘制方框的屏幕时,它全部绘制但只持续了几分之一秒,然后它们就消失了。

非常感谢任何帮助,感谢您花时间阅读本文。

您的 LevelBoxX 会无限大,因此方块 运行 很快就会离开屏幕。您可以像这样在 for 循环之前重置 LevelBoxX:

public void DrawLevelBoxes(SpriteBatch spriteBatch)
{
    LevelBoxX = 20;
    for (int i = 0; i < 10; i++)
    {
        spriteBatch.Draw(levelboxbg.texture, new Vector2(LevelBoxX + 20 ,0), levelboxbg.color);
        LevelBoxX += 20;
    }
}

或者只声明一个局部变量:

public void DrawLevelBoxes(SpriteBatch spriteBatch)
{
    int counter = 20;
    for (int i = 0; i < 10; i++)
    {
        spriteBatch.Draw(levelboxbg.texture, new Vector2(counter + 20 ,0), levelboxbg.color);
        counter += 20;
    }
}