Auto-rotating a game

Note: If you're using the Scaffold project of Sparrow 1.3 or 2.x, auto-rotation is already prepared for you. Find out all about it here.

If your game should support different orientations and be updated automatically when you rotate your device, that's easy to do.

As described here, you achieve the best performance if you don't rotate the complete SPView, but only the content within Sparrow. Have a look at that tutorial to see how it's done.

Get notified of orientation changes

First, tell iOS that you want to be notified when the device's orientation changes. Put the following code in the init-method of your game class:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(onDeviceOrientationChanged:)
    name:@"UIDeviceOrientationDidChangeNotification" 
    object:nil];

React on those changes

Then add the following method to the same class:

- (void)onDeviceOrientationChanged:(UIEvent *)event 
{	
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)deviceOrientation;
 
    // don't remove this, even if you're not displaying the status bar!
    // it has some positive side effects.
    [[UIApplication sharedApplication] setStatusBarOrientation:interfaceOrientation];
 
    // update your game contents here, as described above
    NSLog(@"Device Orientation changed: %i", deviceOrientation);
}

Whenever the device is now turned, that method gets called, and you can update the screen accordingly. (Note that UIDeviceOrientationLeft corresponds to UIInterfaceOrientationRight. Looks strange, but it's not an error.)

If you want to support just a subset of those orientations, modify the method accordingly:

- (void)onDeviceOrientationChanged:(UIEvent *)event 
{	
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
 
    if (deviceOrientation == UIDeviceOrientationPortrait ||
        deviceOrientation == UIDeviceOrientationPortraitUpsideDown)
    {
        // etc.
    }
}

That should do it!

  tutorials/auto-rotating_the_interface.txt · Last modified: 2013/05/30 12:47 by daniel
 
Powered by DokuWiki