0
我正在嘗試開發一個JRPG /地牢爬行器作爲夏季項目,我正在清理我的代碼。在戰鬥中它存在「健康條」,一個健康條由每個角色需要繪製的3個矩形組成(總共2-8個字符,取決於上下文意味着一次最多可以有24個保護矩形)。從xna紋理繪製矩形的不同方法之間的性能差異?
我以前繪製平衡杆的方法是基於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);
}
}
有了新的抽屜類,我可以扔掉了「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));
非常感謝,它解決了這個問題。 – Olle89