0

我正在尝试将 pa JRPG/dungeon crawler 作为夏季项目开发,并且我正在清理我的代码。在战斗中,它存在“生命条”,一个生命条由 3 个需要为每个角色绘制的矩形组成(总共 2-8 个字符,具体取决于上下文意味着一次最多 24 个生命条矩形)。

我绘制愈合条的旧方法是基于 1 个纹理,我从其中获取单个像素并在矩形区域上绘制。基本上我使用“HealtBar”纹理作为调色板......例如,如果源矩形是 (0, 0, 1, 1) 它表示绘制一个黑色矩形。

Texture2D mHealthBar;
mHealthBar = theContentManager.Load<Texture2D>("HealthBar");

public override void Draw(SpriteBatch theSpriteBatch)
        {
            //draw healtbar
            theSpriteBatch.Draw(mHealthBar, new Rectangle((int)Position.X+5,
            (int)(Position.Y - 20), (MaxHealth * 5)+7, 15),
            new Rectangle(0, 0, 1, 1), Color.Black);

            theSpriteBatch.Draw(mHealthBar, new Rectangle((int)(Position.X + 8),
            (int)(Position.Y - 17), ((MaxHealth * 5)), (mHealthBar.Height) - 2),
            new Rectangle(2, 2, 1, 1), Color.White);

            theSpriteBatch.Draw(mHealthBar, new Rectangle((int)(Position.X + 8),
            (int)(Position.Y - 17), ((Health * 5)), (mHealthBar.Height) - 2),
            new Rectangle(3, 2, 1, 1), Color.Red);
      }

这不是一个好看的解决方案……所以我尝试创建一个抽象类,以减少代码量并提高代码的清晰度。

abstract class Drawer
{
    static private Texture2D _empty_texture;

    static public void DrawRect(SpriteBatch batch, Color color, Rectangle rect)
    {
        _empty_texture = new Texture2D(batch.GraphicsDevice, 1, 1);
        _empty_texture.SetData(new[] { Color.White });

        batch.Draw(_empty_texture, rect, color);
    }
}

使用新的 Drawer 类,我可以丢弃“mHealthBar”变量并以更美观的代码方式绘制矩形。但是当我开始使用新方式绘制游戏开始出现帧率问题时,旧方式很流畅......帧率问题的原因是什么?

        Drawer.DrawRect(theSpriteBatch, Color.Black, new Rectangle((int)Position.X+5,
        (int)(Position.Y - 20), (MaxHealth * 5)+7, 15));

        Drawer.DrawRect(theSpriteBatch, Color.White, new Rectangle((int)(Position.X + 8),
        (int)(Position.Y - 17), (MaxHealth * 5), 9));

        Drawer.DrawRect(theSpriteBatch, Color.Red, new Rectangle((int)(Position.X + 8),
        (int)(Position.Y - 17), (Health * 5), 9));
4

1 回答 1

1

问题是您每次要绘制时都在创建新纹理并设置颜色。

您应该做的只是创建一次纹理(在加载其他内容时)。

于 2011-08-02T09:22:11.603 回答