0
\$\begingroup\$

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()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

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

        healthBar = Content.Load<Texture2D>("HealthBar");

        // TODO: use this.Content to load your game content here
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // 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
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        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!

\$\endgroup\$
4
  • 4
    \$\begingroup\$ Set up a timer for 1 second in Update() and decrease the health every time it's called. \$\endgroup\$
    – DMan
    Commented Nov 25, 2012 at 19:18
  • \$\begingroup\$ so would I put somethin like this in my update ... ' seconds += (float)gameTime.ElapsedGameTime.TotalSeconds; if (seconds == 1) { CurrentHealth -= 1; } ' \$\endgroup\$
    – Craig
    Commented Nov 25, 2012 at 19:39
  • \$\begingroup\$ use (seconds >= 1), make sure to reset your seconds back to 0 when the timer is reached. \$\endgroup\$ Commented Nov 25, 2012 at 19:50
  • \$\begingroup\$ 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. \$\endgroup\$
    – DMan
    Commented Nov 25, 2012 at 19:55

2 Answers 2

3
\$\begingroup\$

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;
}
\$\endgroup\$
4
  • \$\begingroup\$ perfect, cheers! :D \$\endgroup\$
    – Craig
    Commented Nov 25, 2012 at 19:59
  • \$\begingroup\$ 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. \$\endgroup\$
    – Philipp
    Commented Nov 25, 2012 at 20:21
  • \$\begingroup\$ 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. \$\endgroup\$
    – DMan
    Commented Nov 25, 2012 at 21:31
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 22, 2013 at 8:50
0
\$\begingroup\$

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();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .