I’ve been meaning to make a timer utility class to better manage my game timers, and I thought I’d share it with everyone else. I’m sure most, if not all, of you guys have probably made your own timers for your games, but here’s one that I made in case you want to use it. It’s a simple timer, that only needs to be updated, but has an option as to what type of timer it is (ie. run once, run forever in cycle). I’m posting this because someone asked me to, but anyone is free to use it if they want.
using Microsoft.Xna.Framework;
namespace Utility
{
///
/// What the timer does. If a type isn't provided to the timer, it's assumed to be RUNANDSTOP.
///
public enum TimerType
{
///
/// RUNANDSTOP runs the timer until it finishes then sets isActive to false and sets justFinishedCycle.
///
RUNANDSTOP,
///
/// RUNANDSTOP runs the timer until it finishes then sets justFinishedCycle. Does not set isActive to false and will continue to update.
///
RUNANDCONTINUE,
///
/// CYCLE runs forever but when the timer reaches its length resets and sets justFinishedCycle.
///
CYCLE
}
public class Timer
{
float time = 0;
float length;
TimerType type;
bool isActive;
bool justFinishedCycle = false;
public Timer(float length)
{
this.length = length;
this.isActive = true;
type = TimerType.RUNANDSTOP;
}
public Timer(float length, TimerType type)
{
this.length = length;
this.isActive = true;
this.type = type;
}
public Timer(float length, bool isActive)
{
this.length = length;
this.isActive = isActive;
}
public Timer(float length, bool isActive, TimerType type)
{
this.length = length;
this.isActive = isActive;
this.type = type;
}
public float Time
{
get { return time; }
set { time = value; }
}
public float Length
{
get { return length; }
set { length = value; }
}
public TimerType Type
{
get { return type; }
set { type = value; }
}
public bool IsActive
{
get { return isActive; }
set { isActive = value; }
}
public bool JustFinishedCycle
{
get { return justFinishedCycle; }
set { justFinishedCycle = value; }
}
public void Update(GameTime gameTime)
{
justFinishedCycle = false;
if (isActive)
{
if (time < length)
{
time += (float)gameTime.ElapsedGameTime.TotalSeconds;
}
else if (type == TimerType.CYCLE)
{
time += (float)gameTime.ElapsedGameTime.TotalSeconds;
time %= length;
justFinishedCycle = true;
}
else if (type == TimerType.RUNANDCONTINUE)
{
justFinishedCycle = true;
}
else if (type == TimerType.RUNANDSTOP)
{
isActive = false;
justFinishedCycle = true;
}
}
}
}
}