Health Bar & XP Bar[Solved]

Hello Everyone,

My game has a health bar and an xp bar. I want to keep the health bar at a width of 150 but my health is 100. How would i make it so if the enemy shoots me it takes 10 away from my health leaving me with 90 health left. rather than making the health bar 100px wide and taking 10 away from that. because i want to be able to have health buffs in the future.

So how do i keep the health bar a static width and change the health bar size by the amount of health my enemy is dealing. Please help

Thanks

  • GlennBrann

int health = 100;
int width = 150;
float ratio = width/health;
float healthWidth;

public void update(){
     healthWidth = ratio * health;
}

You could get the percent of life left (which will be easy since you are using 100 as maximum) and set that percent of 150 to be drawn
So when the player has 90 health, .9 * 150 width of the health bar would be drawn

When ever my health is over the width of the health bar it doesn’t render.
for example:

the bar with is 100px.
the player health 150 health points.
i did what you said and its not rendering…

It would be really helpful if you could share your health bar rendering code ;).

Sorry, i’m just drawing a rectangle with and the width would be the width of 100 but my health is 150.

g.fillRect(211, 6, (int)healthWidth, barHeight);

I thought you said in your first post that the width is 150 and health is 100? :stuck_out_tongue:

[quote=“GlennBrann,post:1,topic:43053”]
Try something like:

int maxHealth, currentHealth, barWidth;

maxHealth = 150;
currentHealth = /*whatever the current health of the character is*/
barWidth = 100;

float ratio = currentHealth/maxHealth;

g.fillRect(211, 6, (int)(ratio*barWidth), barHeight);

Basically, what you want is to get the ratio of the player’s current health against his maximum health and multiply that to the width of the bar.

So if the player has 75 health remaining for example, the width of your bar should be:

= (currentHealth/maxHealth)*barWidth
= (75/150)*100
= 50px

It works like a charm… :slight_smile: thank you everyone. PS sorry for being not clear enough in the original post.

  • GlennBrann

Wouldn’t you want to do 75/100 * 150? Because 75 health should be about 113px.

Well, he clarified that his health is 150 units and the bar is 100px… so if he has 75 units of health left, which is 50% of 150 units, his health bar should be 50px, which is 50% of 100px.