Foreach循环导致滞后?

时间:2016-07-25 19:01:24

标签: c# xna

在上一个问题here.中,我成功地找到了如何从图像中读取和绘制每个帧的关卡。

现在我已经输入了一个Player类,尽管代码没有这样做,但玩家的动作仍然非常不稳定。我知道这一点,因为如果我对水平读数代码进行评论,则播放器移动正常。

我认为这是foreach循环这样做的。我不知道,我们将不胜感激!

为了节省您点击的时间,这是我成功读完水平的代码。

public void readLevel(string path, GraphicsDevice graphics)
{

    //GET AN ARRAY OF COLORS
    Texture2D level = Content.Load<Texture2D>(path);
    Color[] colors = new Color[level.Width * level.Height];
    level.GetData(colors);

    //READ EACH PIXEL AND DRAW LEVEL
    Color brickRGB = new Color(128, 128, 128);
    Color blankRGB = new Color(87, 0, 127);

    int placeX = 0;
    int placeY = 0;

    foreach (Color pixel in colors)
    {
        SpriteBatch spriteBatch = new SpriteBatch(graphics);
        spriteBatch.Begin();

        if (pixel == brickRGB)
        {
            Texture2D brick = Content.Load<Texture2D>("blocks/brick");
            spriteBatch.Draw(brick, new Rectangle(placeX, placeY, 40, 40), Color.White);

            Rectangle rect = new Rectangle(placeX, placeY, 40, 40);
            blocks.Add(rect);
        }
        else if (pixel == blankRGB)
        {
            Texture2D back = Content.Load<Texture2D>("titlescreen/back");
            spriteBatch.Draw(back, new Rectangle(placeX, placeY, 40, 40), Color.White);
        }

        if (placeX == 840)
        {
            placeX = 0;
            placeY += 40;
        }
        else placeX += 40;
        spriteBatch.End();
    }
}

Game.cs:

class Game
{
    Player player;
    LevelReader reader;
    int level = 1;

    public Game(ContentManager content)
    {
        reader = new LevelReader(content);
        player = new Player(content);
    }

    public void Update()
    {
        player.Update();
    }
    public void Draw(GraphicsDevice graphics)
    {
        reader.readLevel("levels/l" + level, graphics);
        player.Draw(graphics);

    }
}

1 个答案:

答案 0 :(得分:1)

您可能希望将调用移至循环外的spritebatch.Begin()spritebatch.End()

SpriteBatch spriteBatch = new SpriteBatch(graphics);
        spriteBatch.Begin();
foreach (Color pixel in colors)
    {


        if (pixel == brickRGB)
        {
            Texture2D brick = Content.Load<Texture2D>("blocks/brick");
            spriteBatch.Draw(brick, new Rectangle(placeX, placeY, 40, 40), Color.White);

            Rectangle rect = new Rectangle(placeX, placeY, 40, 40);
            blocks.Add(rect);
        }
        else if (pixel == blankRGB)
        {
            Texture2D back = Content.Load<Texture2D>("titlescreen/back");
            spriteBatch.Draw(back, new Rectangle(placeX, placeY, 40, 40), Color.White);
        }

        if (placeX == 840)
        {
            placeX = 0;
            placeY += 40;
        }
        else placeX += 40;

    }
spriteBatch.End();