Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

How do I set a game timer in XNA? I need it to keep the game in sync no matter the lag or frame rate to prevent one moment to be normal but the next everything is sped up.

share|improve this question
2  
You don't have to. XNA already did. Use the gameTime parameter given to you in the update/draw methods. –  Gustavo Maciel Nov 1 '12 at 10:13

2 Answers 2

As Gustavo mentioned, you can use gameTime in Draw and Update. You may also write your own small timer class, which gets updated with the gameTime (and simply adds it up). This makes sense if you want to add some more logic to your timer class, like events or callbacks.

share|improve this answer

I was doing a quick Google Search and came across this question - I just figured I'd drop my code here. Hopefully this will be useful someone else wandering by:

using System;
using Microsoft.Xna.Framework;

namespace PuzzleGame.Utilities
{
    /// <summary>
    /// A <see cref="GameTimer"/> provides callbacks for when a certain amount of time has elapased.
    /// This is useful for things like time limited games, delayed menu transitions and the like.
    /// </summary>
    public class GameTimer
    {

        /// <summary>
        /// Initializes a new <see cref="GameTimer"/>
        /// </summary>
        /// <param name="totalSeconds">The amount of time it will take for this timer to fire off.</param>
        public GameTimer(double totalSeconds)
        {
            TotalSeconds = totalSeconds;
        }


        /// <summary>
        /// This event fires off when the <see cref="GameTimer"/> has completed. 
        /// </summary>
        public EventHandler Completed;

        /// <summary>
        /// The amount of total seconds this timer takes to fire off.
        /// </summary>
        public double TotalSeconds { get; set; }

        /// <summary>
        /// The amount of progress [0 .. TotalSeconds] that the timer has made at the current polltime.
        /// </summary>
        public double TotalProgressSeconds { get; set; }


        /// <summary>
        /// Updates the timer with the given <see cref="GameTime"/> state.
        /// </summary>
        /// <param name="gameTime"></param>
        public void Update(GameTime gameTime)
        {
            TotalProgressSeconds += gameTime.ElapsedGameTime.TotalSeconds;
            if (TotalProgressSeconds >= TotalSeconds)
                Completed(null, null);
        }


    }

}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.