# XNA Health Bar continually decreasing

As per the Health bar tutorial on ... http://www.xnadevelopment.com/tutorials/notsohealthy/NotSoHealthy.shtml

I have set up the above, how do I make it decrease by 1 health per second?

I want to create a mini survival game, and this is an important factor.

Where am i going wrong? I want it to visibly decrease every second.

    using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Health
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;

Texture2D healthBar;
int currentHealth = 100;
float seconds;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content.  Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{

base.Initialize();
}

/// <summary>
/// LoadContent will be called once per game and is the place to load
/// </summary>
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);

}

/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
{
// TODO: Unload any non ContentManager content here
}

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
this.Exit();

currentHealth = (int)MathHelper.Clamp(currentHealth, 0, 100);

seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
currentHealth -= 1;
}
seconds = 0;

base.Update(gameTime);
}

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, healthBar.Width, 44), new Rectangle(0, 45, healthBar.Width, 44), Color.Gray);
spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, (int)(healthBar.Width * ((double)currentHealth / 100)), 44), new Rectangle(0, 45, healthBar.Width, 44), Color.Red);
spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, healthBar.Width, 44), new Rectangle(0, 0, healthBar.Width, 44), Color.White);
spriteBatch.End();

base.Draw(gameTime);
}
}
}


Cheers!

• Set up a timer for 1 second in Update() and decrease the health every time it's called. – DMan Nov 25 '12 at 19:18
• so would I put somethin like this in my update ... ' seconds += (float)gameTime.ElapsedGameTime.TotalSeconds; if (seconds == 1) { CurrentHealth -= 1; } ' – Craig Nov 25 '12 at 19:39
• use (seconds >= 1), make sure to reset your seconds back to 0 when the timer is reached. – Luis Estrada Nov 25 '12 at 19:50
• You would have to keep track of the difference between TotalSeconds and the current seconds to determine if 1 second has passted. If you used ElapsedGameTime.Seconds, then it would probably never run because the update between each frame is most likely only a few milliseconds. – DMan Nov 25 '12 at 19:55

You could do this using a float.

At the top of your Game1.cs, add:

float timer = 0f;


Then in Update:

timer += gameTime.ElapsedGameTime.Milliseconds;
if (timer >= 1000) // Your time, in milliseconds
{
mCurrentHealth -= 1;
timer -= 1000;
}

• perfect, cheers! :D – Craig Nov 25 '12 at 19:59
• This solution doesn't look right to me. 1. you seem to assume that gameTime.ElapsedGameTime.Milliseconds; gets reset to 0. Doesn't it increase more and more while the game is running? 2. when more than 1000 milliseconds elapsed, let's say 2200, you still only reduce the health by one. It should be decreased by 2, and the 200 remaining ms should be somehow carried over to the next loop iteration. – Philipp Nov 25 '12 at 20:21
• 1. gameTime.ElapsedGameTime.Milliseconds gives the elapsed game time since the last update. It will be reset to zero every frame automatically. 2. I agree with you on this; I considered it. However, I doubt it's 'normal' for a frame to take more than a few milliseconds to update, and so the timer will be off by only a maximum of those few milliseconds, not seconds. As a quick fix, just subtract 1000 as opposed to resetting to zero. – DMan Nov 25 '12 at 21:31
• This is good IF you want a stepping decrement. But as the OP does not specify this, we can asume that making currentHealth a float and decreasing it by ElapsedGameTime.TotalSeconds will do the trick. – Stig-Rune Skansgård Mar 22 '13 at 8:50

The reason YOUR code doesn't work is this:

seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
currentHealth -= 1;
}
seconds = 0;


You reset seconds every frame, so it can NEVER be >= 1. seconds = 0; should be inside your if. THat would fix it. Like this:

seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
currentHealth --;
seconds = 0;
}


However, I have a more elegant solution to your problem, if you want your HP-bar to decrease smoothly;

replace:

int currentHealth = 100;


with:

float currentHealth = 100;


Replace

seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
currentHealth -= 1;
}
seconds = 0;


with

//DeltaTime = Change in time. (delta means "change in" in physics/maths)
//This is always usefull in physics calc etc, so keep it and pass to other objects update instead of gametime:
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

if (currentHealth > 0)
currentHealth = Math.Max(0f, currentHeath - deltaTime);
else
Die();