How to reset SDL_GetTicks SDL 2.0 ?

Hi, I wanted to create a time counter for my simple game which would reset to zero every time it reaches 50 seconds.

In my main function handling events and everything else I added variable startTime and elapsedTime:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void startFrogger()
{
	double startTime, elapsedTime;
	int lives = 3, places = 0;
		
	bool quit = false, play = true, paused = false;
	SDL_Event myEvent;
	SDL_Event pauseEvent;
	while (!quit)
	{
		elapsedTime = SDL_GetTicks() / 1000;


	while (SDL_PollEvent(&myEvent) != 0)
	{
         //handling events...
				
	}		
	
printf("elapsed = %f \n", elapsedTime);

        //some render functions

        }
}


My big question: is there a way to "reset" this timer when the time reaches 50 seconds? In game I'd like it to work this way:
-> counter is counting seconds to 50
-> if player didn't win the game in 50 seconds he loses one of his 3 lifes and plays again
-> when the player loses life the counter resets to zero so the player has another 50 seconds
-> if the player won the game and wants to play again timer is set to 0 seconds too

I couldn't figure out how to make this work... Thanks for ideas!
Last edited on
At the beginning of when you want to start recording the time, call startTime = SDL_GetTicks() / 1000.0;
Later on, do something like:
1
2
3
4
5
6
7
8
double currentTime = SDL_GetTicks() / 1000.0;
if (currentTime - startTime > 50.0)
{
    // lose a life
    // reset game state
    // restart timer
    startTime = SDL_GetTicks() / 1000.0;
}
Last edited on
Thank you for help @Ganado, that works!
I have a question though, I put startTime variable at the beginning of my startFrogger() function, just after {. And, the value of startTime is very small and not constant - something around 0,1-0,2 seconds. Should it work this way?

And one more question, when the player loses game before the counter reaches 50 seconds, and wants to play again - how reset the timer?
This is how it looks now in my code:
1
2
3
4
5
					if (currentTime - startTime > 50.0)
					{
						gameOver(&otherRect[0], &lives, &play, &places);
						startTime = SDL_GetTicks() / 1000.0;
					}


gameOver function subtracks one life from player and then checks if player still have lifes > 0 to play. If player lost all his lifes and wants to play again, then inside gameOver function is called startFrogger() function which handles the game again... I find myself a little lost in how to reset this time in this situation :/
Topic archived. No new replies allowed.