A Note about Timer

0 views

Main components of a Timer class implemented in C++. I used to have a hard time thinking this through, so I guess I’d better keep a note of it.

// Private variable needed
Unit32 startTicks = 0; // This is indeed the starting time
Unit32 pausedTicks = 0; // This is indeed the length of pasued time
bool started; // This is not illustrated in this example
bool pasued;

// Note: SDL_GetTicks() will return the current clock time; it is given by the SDL library (std library time.h also works)

// Three key functions shown below

Timer::pause() {
	if (!pasued) {
		paused = true;		
		// How long the timer has started;
		// When pause() is called, the timer screen freezes to display this time
		pausedTicks = SDL_GetTicks() - startTicks;
		// When pasue() is called, startTicks initializes
		startTicks = 0;
	}
}

Timer::unpause() {
	if (paused) {
		pasued = false;
		// Subtract the paused time, as if it never pauses
		startTicks = SDL_GetTicks() - pausedTicks;
		// Paused time for this round is no longer needed after we unpause the timer
		pausedTicks = 0;
	}
}

Unit32 Timer::getDisplayTime() {
	Unit32 time = 0;
	if( paused ) {
		// When pasued, display this fixed value
		time = pausedTicks;
	}
	else {
		// Normal case, simply subtracting starting time from current time
		time = SDL_GetTicks() - startTicks;
	}
}

Hopefully this is a sufficiently clear explanation of how a timer works!

PREVIOUSDoxygen CheatSheet
NEXTProgramming Basics 编程的一些基本常识