I have a simple timer class in a game, intended to allow me to make an entity do something every so many seconds. It has two functions:
void Timer::GameTimer() // Gets time between frames
{
::ElapsedTime = Clock.GetElapsedTime();
Clock.Reset();
}
This just updates the ElapsedTime Global so that it can be grabbed by anything that needs it. It’s placed inside the gameloop.
Then the important one:
bool Timer::tCounter(int total) // Returns true every 'total' seconds
{
static float ftime; // Variable to hold the mounting elapsed time
static int n; // Counter variable for true trigger
ftime += ElapsedTime;
int itime = (int)ftime; //Truncate
if(!(itime%total) && itime != 0)
{
n++;
}
else
{
n = 0;
}
if (n == 1)
{
return true;
}
else
{
return false;
}
}
Timer is instantiated inside the Entity class as Timer::Timer timer
The function is then called inside Entity::Update once per loop for every instance of the entity class in the game:
if (timer.tCounter(2))
{
Do stuff
}
The problem is it doesn’t seem to count uniquely for each instance of Entity, resulting in only one doing stuff at a time and other weird stuff occasionally happening. The problem seems to be the static variables being shared. How do I ensure that this tCounter function holds unique variables for each instance that calls it?
static in this context means only one instance of something exists at a time and is initialized once.
The easiest fix to me would be to (not necessarily the best fix):
– Remove the static qualifier
– make
ftimeandnmember variables ofTimer– Create an instance of
Timerfor each entity that you want to react to a timer.