Reputation: 678
I am trying to developing p a JRPG/dungeon crawler as a summer project and I am atm cleaning up in my code. In the combat it exists "healthbars" and one healthbar consists of 3 rectangles that need to be drawn for each character (2-8 characters in total depending on the context means up to 24 healbar rectangles at one time).
My old way to draw the healbar was based on 1 texture where i took a single pixel from and draw over a rectangle shaped area. Basicly i used the "HealtBar" texture as a color palet... for example if the source rectangle was (0, 0, 1, 1) it represented to draw a black rectangle.
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);
}
this aint a good looking solution... so instead i tried to create an abstract class that would reduce the amount of code and increase the amount of clarity in the code.
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);
}
}
With the new Drawer class I could throw away the "mHealthBar" variable and draw the rectangles in a more nice looking code way. But when I started to use the new way to draw the game started to have frame Rate problems, the old way was smooth...what is the reason to the frame rate problems?
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));
Upvotes: 0
Views: 592
Reputation: 32438
The issue is that you're creating a new texture and setting the colour every time you want to draw.
What you should do is only create the texture once (when loading your other content).
Upvotes: 1