Search code examples
c#xna

Health Bar XNA C#


Here is my code

healthBarPosition = new Vector2(0, 550); 
public Texture2D healthGaugeTexture; 
public Texture2D healthBarTexture; 
public Texture2D healthGaugeTexture;

public int maxHealth;
public int currentHealth = 500;

In load Method;

healthGaugeTexture = Content.Load<Texture2D>("HealthBar Gauge");
healthBarTexture = Content.Load<Texture2D>("Health Bar");

In Draw Method;

    spriteBatch.Draw(healthGaugeTexture, healthBarPosition, Color.White);
spriteBatch.Draw(healthBarTexture, healthBarPosition, Color.White)

This Draws Full Health bar within Health Gauge.

I've tried to

spriteBatch.Draw(healthBarTexture, healthBarPosition, 
                 new Rectangle((int)healthBarPosition.X, (int)healthBarPosition.Y,
                               currentHealth, healthBarTexture.Width), 
                 Color.White);

Or

spriteBatch.Draw(healthBarTexture, healthBarPosition, 
                 new Rectangle((int)healthBarPosition.X, (int)healthBarPosition.Y,0,0),
                 Color.White);`

When is like this it's just Health Gauge without health bar...bar is somewhere behind gods legs.... xD I do not know where is Source Rectange or where did i set it.

I also tried

https://www.youtube.com/watch?v=C9ldaOGjePE

Same as this video and

Maxhealth = healthBarTexture.width;

Gives me error, so I removed the comment and it works.

What I want is to draw full health with set health value i.e.: Current health = 100; but health bar to be full I can draw with just with Rectangle and problem is that i do now know how to use source rectangle and where to place it


Solution

  • You just need to draw using a clipping rectangle.

    There are many overloads of SpriteBatch.Draw that allow you to set the source and destination rectangle. Heres one: (MSDN)

    By shrinking the source and destination rectangle, you will give the illusion of a "variable length" health bar. You will likely want to fix the "Left" property, and shrink or grow the "Width" property of each rectangle to get your effect.

    When setting up the source rectangle, be careful to set it up so that you are not "off" the texture. To try and explain what I mean when I say a source rectangle can be "off" of the texture, consider the following image:

    enter image description here

    The Green rectangle is "Off" of the texture, and is similar to what can happen with the code you posted. The cyan rectangle is what you want to happen.