I'm making a health bar for my little game and because I wanted something nicer looking, instead of simply using fillrect I have an empty framed health bar as a BufferedImage and I draw small pieces of gradiented bar (another BufferedImage) inside the empty bar frames. The amount of bar pieces needed to draw depends on how much HP the player has left, so the maximum amount of pieces to draw is 100.
So every game loop update, it checks the player's HP and then goes through a loop to draw as many tiny pieces of a health bar as is needed. I'm thinking this can't be efficient and is at least one of the reasons my screen update is getting jerky at times.
What I'd like to do instead, is go through that loop to build a health bar according to the actual hp, then save the result as a new BufferedImage and draw that one on the screen instead. But I can't figure out how to do this.
Instead of drawing the small pieces over and over again, I would then in the game loop only draw the previously generated BufferedImage and generate a new one only if the player's HP has actually changed since the last one was generated.
This make sense? How would I generate a new BufferedImage for a bar which is already filled out by the correct amount?
Here's the current loop to draw the health bar for reference. This can't be efficient. getHpBarSprite() and getHpPortionSprite() return BufferedImages that have been loaded from PNG's. getHpLeft() returns the percentage of HP left.
The free horizontal space inside the hp bar sprite is 200 pixels and the hp portion sprite is 2 pixels wide (not 100 pixels and 1 pixel because then the bar would've been too small to my taste..)
g.drawImage(gameResources.getHpBarSprite(), 10, 10, null);
for (int x = 0; x < playerPlane.getHpLeft(); x++)
g.drawImage(gameResources.getHpPortionSprite(), 12+x*2, 12, null);
This is what it looks like at 20% HP left. It does exactly what I want, but I want to do it in a better way so that I wouldn't have to go through that stressful drawing loop every single game loop iteration..
I'm just now starting to build the actual HUD starting with the HP bar so don't mind those messy ammo/lives etc texts visible in the pic..