I've drawn a Health Bar before and had it drain/refill on a button press using if statements and rectangles.
First I loaded the image, then I set a new rectangle to be equal to the image's height and width.
greenHealth = Content.Load<Texture2D>("GreenHealth");
redHealth = Content.Load<Texture2D>("RedHealth");
blackHealth = Content.Load<Texture2D>("BlackHealth");
jumpGuy = Content.Load<Texture2D>("JumpGuy");
enemyBlock = Content.Load<Texture2D>("Block");
greenRectangle = new Rectangle(0, 0, greenHealth.Width, greenHealth.Height);
redRectangle = new Rectangle(0, 0, redHealth.Width, redHealth.Height);
blackRectangle = new Rectangle(0, 0, blackHealth.Width + 5, blackHealth.Height + 5);
Then I set it to drain/refill based on key presses -
public void healthDrain()
{
if (Keyboard.GetState().IsKeyDown(Keys.Space))
{
greenRectangle.Width -= 2;
}
if (Keyboard.GetState().IsKeyDown(Keys.Space))
{
redRectangle.Width -= 1;
}
if (Keyboard.GetState().IsKeyDown(Keys.L))
{
redRectangle.Width = greenRectangle.Width;
}
if (Keyboard.GetState().IsKeyDown(Keys.R))
{
greenRectangle.Width += 1;
}
if (greenRectangle.Width > blackRectangle.Width - 4)
{
greenRectangle.Width = blackRectangle.Width - 4;
}
}
The Result is a Health Bar that can be drained/refilled -
The problem arises when I want the health to drain/refill based on the Player Health, which I set to 100. I do not know how to properly implement this and attempts at it have resulted in it functioning incorrectly, like the health draining on its own, or not moving at all.
I intend to have the player take damage when in contact with the yellowish-green block in the image. I did this using rectangles and an if statement with rectangle.Intersect.
if (jumpRect.Intersects(enemyRectangle))
{
playerHealth--;
}
I tried having the health bar's width be equal to the playerHealth value but it didn't work and I'm unsure of how to make it work correctly.
I do hope I was able to make this easy for someone to help me solve.