1
\$\begingroup\$

Creating a simple survival game.

When the player has been caught I want to display the amount of seconds that they survived for.

How do I go about this?

\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

When your round starts, save the current time, e.g. copying DateTime.Now.

Once the round is over, compare your old value with the current DateTime.Now and you should end up with the time span representing the length of the game (keep in mind that the precision is limited and different based on your operating system, but it's usually around 10-16 ms).

\$\endgroup\$
4
\$\begingroup\$

One fairly simple way to do this is to just make a variable called "SecondsSurvived" to either Player class or GameplayScreen/whatever. Then in the update method, if the game is not paused/stopped/ended, increment SecondsSurvived variable by ElapsedTime. Then when the player dies, simply use that SecondsSurvived variable as you like. So something like this:

public class GameplayScreen
{
     private float _secondsSurvived = 0f;
     private Player _player;

     ...

    public void Update(GameTime gameTime)
    {
         ...

         if(_player.IsAlive && this.IsActiveScreen)
         {
              _secondsSurvived += (float)gameTime.ElapsedGameTime.TotalSeconds;
         }
    }
}

Remember to reset _secondsSurvived to zero everytime the game restarts.

\$\endgroup\$

You must log in to answer this question.

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