XNA - 绘制许多矩形会导致滞后



我正在XNA中创建一个游戏,需要绘制数千个小矩形/正方形。随着数量的增加,性能会变差。这是我当前使用的代码:

protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            foreach (SandBit sandBit in sandBitManager.grid)
            {
                Point p = sandBit.Position;
                spriteBatch.Draw(square, new Rectangle(p.X, p.Y, sandBit.SIZE, sandBit.SIZE), Color.White);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }

我为每个方块调用spriteBatch.Draw(),并且我正在重新绘制整个屏幕只是为了添加一个正方形。我已经做了大量的搜索,我相信一个解决方案是绘制到一个纹理,然后在该纹理上调用Draw(),但我找不到相关的示例。

尽量不要在绘制函数中调用 Rectangle 构造函数,您可能会从中获得很大的性能提升(只需一遍又一遍地使用相同的矩形对象,为属性设置不同的值)。

鉴于这是一个2D游戏(没有粒子或任何东西),您可能需要考虑为沙子使用更大的预生成纹理,而不是大量小矩形。无论您做什么,在绘制循环中拥有大量枚举最终都会赶上您。

        Rectangle sandBitRect = new Rectangle()
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            foreach (SandBit sandBit in sandBitManager.grid)
            {
                Point p = sandBit.Position;
                sandBitRect.Left = p.X;
                sandBitRect.Top = p.Y;
                sandBitRect.Width = sandBit.SIZE;
                sandBitRect.Height = sandBit.SIZE;
                spriteBatch.Draw(square, sandBitRect, Color.White);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }

最新更新