
As Einstein has taught us Time is not Simple.It squishes and expands depending on how fast or how close we are to a gravitational sources. That said in programming it should be easy… But…
For the last weeks before submitting Dragon Emperor’s Challenge to the App Store, I’ve been fighting with Time.
Initially I programmed a timer by incrementing a counter every second.
Ala:
totalTimeInSeconds=0;
myTimer = [NSTimer scheduledTimerWithTimeInterval:
(1-(4/12)) // this is the time it take the animation to complete //
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
-(void)updateTimer
{
totalTimeInSeconds++;
// do update display stuff //
}
So simple. Stop incrementing totalTimeInSeconds when you want to pause. To save the time just save the integer value and restart it. Unfortunately due to rounding time delays in animation it sometimes it skips and basically doesn’t keep good time. So I had to what I am calling calculated time.
Where I store the date/time the timer is started.
startTime = [NSDate date];
Which is great if you don’t exit the game. But of course at sometime; why? I don’t know, but you may need to exit. Dragon Emperor’s Challenge. So you need to save the the amount of time on the clock. In defaults as a Double.
// Save the pause time interval //
NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
[defaults setDouble:currentTime forKey:@”currentTime”];// then when you restart the clock //
// reset the Date to now //
startTime = [NSDate date];
NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
currentTime = [defaults doubleForKey:@”currentTime”];
// and here is the key –> subtract the previous time on the clock from the current time
startTime = [[startTime dateByAddingTimeInterval:((-1)*(currentTime))]retain];
currentTime=0; // reset the currentTime.// restart the timer //
myTimer = [NSTimer scheduledTimerWithTimeInterval:(1-(4/12))
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
What’s a pain is that you need to pause/restart the timer when the app exits, wakes, switches, sleeps. and beta test for all that, including crashes and low memory warning.
** Just a note about sloppy programming. Before I had a number of flags that told me when Dragon Loaded and slept etc. Which meant I was trying to bandaid(tm) around all the options, sometimes subtracting the time, sometime not.. depending on the flag.. well that was a nightmare. Just Hack the arm off and replace it with something that does work instead putting patches on patches or in this case a plethora of if else if if statements !!!
So Time isn’t Simple, and it will make your brain hurt thinking about it. but also challenging and fun.. which is what keeps us alive.