Hi there,
I have a healthBar in my 2D game. My original plan was to have the bar’s health points, see pic, made up, each by a sprite. There are 25 sprites that make up the meter. My thought was if, 4 pts damage given, remove one bar.
My question is this, It will require to continually calculate the percentage of damage done, then ask, if damageDone == this… a bunch of times over. So My question is, is there a much easier way to gather this information than as I am doing it?
Case does not work for intervals. Not matter how you do it, you will need several if’s. As you try to avoid them at one place, you usually end up and need them somewhere else. You can’t avoid them.
So, I am building for mobile.
I suppose I should have ran tests first but it is the code regardless, of creating 25 comparisons. if(x y). I was just hopeful something could ease it.
No worries.
@appels, fir my case, no pun intended, this might be much better as it will save me using and, sifting thru each if, until it finds the correct answer.
This is not tested code, and maybe it should be “>=”, but it is just to give you an idea about how to approach this without having to write every single “if”. Get back to me if you have any troubles
No, Kragh is not Klingon, sadly Or maybe it is, and I just don’t know about my past… Anyways, glad you could use the approach, and hope this will help you generally in your approach to other problems.
int spritesToDraw = CalculateNumberOfSprites(); // Figure out how many you should draw. Probably integer division will do it.
int xPos = 0;
for (int spritesDrawn = 0; spritesDrawn < spritesToDraw; i++) {
// Draw a sprite at xPos
// Move xPos over a bit
}
In the vast majority of cases if your design necessitates a long stack of if statements you’re making life very difficult for yourself.
Edit: If this is for mobile and you’re using OnGUI this approach could be pretty intense performance wise. Not sure about Unity 4, but in Unity 3 each OnGUI draw is a new draw call, which makes it a pretty expensive way to draw a health bar.
On a lighter note, I have a question. I am using this code to adjust the wpnHudMeter when a new wpn is selected. However, it always takes the firsrt node off even if the energy level is full and I am unsure why. Any reasons you can see?
but you can use a simple div/mod system (aka % and /) to call a method that takes a parameter of type int or float or whatever… I notice you use intervals of 4, so a simple Array of RendererOfHealthBarMetterNodes (phew that’s a mouthfull) can be activated based on that quotient (not sure that’s the right translation).