Building a Game Loop in iPhone and iPad Game Development - dummies

Building a Game Loop in iPhone and iPad Game Development

By Neal Goldstein, Jon Manning, Paris Buttfield-Addison

Part of iPhone and iPad Game Development For Dummies Cheat Sheet

A game loop gets your code to update the game world on your iPhone or iPad many times a second — fast enough to make it look like fluid motion to the player.

To do this, you need to update the position of all your views every time the screen is redrawn by iOS. To be notified of when this happens, you need to use a CADisplayLink class. CADisplayLink is an object that, when you create it, sends your class a message just before the screen is about to update. This gives you the opportunity to move your views around.

To set up a CADisplayLink.

  1. Create a method that gets called when the screen updates; make the method look like this:

    (void) update:(CADisplayLink*)displayLink {
  2. When your view is loaded, create and prepare a CADisplayLink object by adding this code to the viewDidLoad: method in your view controller’s .m file:

    displayLink = [CADisplayLink displayLinkWithTarget:self 
    selector:@selector(update:)]; [displayLink addToRunLoop:[NSRunLoop mainRunLoop]

When your view loads, you receive the update: message many times a second, which is your opportunity to update the game world.