I'm looked a far deal around the internet discussing creating game loops in Cocoa. Most of the game loops I've seen use NSTimer to trigger an event every 60th of a second. Why does there appear to be no examples that use Grand Central Dispatch, like in the source code from Apple's Developers Documentation below. Is there a problem that I don't know about?
dispatch_source_t CreateDispatchTimer(uint64_t interval,
uint64_t leeway,
dispatch_queue_t queue,
dispatch_block_t block)
{
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0, 0, queue);
if (timer)
{
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway);
dispatch_source_set_event_handler(timer, block);
dispatch_resume(timer);
}
return timer;
}
This does not really answer your question, but a regular timer is not the perfect game loop solution (though it might be the easiest one). There is a very good article about game loop programming and two previous questions about game loops on SO that might give you better ideas.
The main point is running the game loop on a separate thread in a loop and recalculate the game model according to the time elapsed between the iterations:
- (void) gameLoop
{
while (running) {
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
CFTimeInterval deltaTime = now - lastTime;
[self updateModelWithDelta:deltaTime];
[self renderFrame];
lastTime = now;
}
}
This will give you maximum smoothness. Read the linked sources for more information, writing a nice threaded game loop is not hard and makes a big difference, IMHO.
This is what I think the answer is. I wish nacho4d would have posted it as an answer so I could green it, but I'm using this opportunity to get the self-learner Skinner Box reward.
Maybe because NSTimer is more famous, less frightening than GCD and because GCD is only MacOS10.6.x/iOS4.x and above only? – nacho4d Feb 13 at 8:01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With