I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer.
So my question is what is the best alternative to using NSTimer?
One alternative per answer please.
Game loop is the main process of all the game rendering threads. It's present in all modern games. It drives input process, internal status update, rendering, AI and all the other processes. Game Loop pattern ensures that game time progresses in equal speed in all different hardware setups.
If you were to only update on user input, the game would only react when the user was providing input. Other game components such as A.I game objects would not react on their own. A loop is therefore the easiest and best way of updating a game.
You can get a better performance with threads, try something like this:
- (void) gameLoop { while (running) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self renderFrame]; [pool release]; } } - (void) startLoop { running = YES; #ifdef THREADED_ANIMATION [NSThread detachNewThreadSelector:@selector(gameLoop) toTarget:self withObject:nil]; #else timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60 target:self selector:@selector(renderFrame) userInfo:nil repeats:YES]; #endif } - (void) stopLoop { [timer invalidate]; running = NO; }
In the renderFrame
method You prepare the framebuffer, draw frame and present the framebuffer on screen. (P.S. There is a great article on various types of game loops and their pros and cons.)
I don't know about the iPhone in particular, but I may still be able to help: Instead of simply plugging in a fixed delay at the end of the loop, use the following:
You might want to have an alert mechanism that lets you know if you're timing is too tight(i,e, if your sleep time after all the compensating is less than 0, which would mean you're taking more time to process than your frame rate allows). The effect will be that your game slows down. For extra points, you may want to simplify rendering for a while, if you detect this happening, until you have enough spare capacity again.
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