Search code examples
iosxcodecocos2d-iphoneios6device-orientation

iOS 6 - How to run custom code when orientation changes


I'm creating a game that allows the device to be in either landscape-left or landscape-right orientation, and the player can change the orientation while it's paused. When they do I need to change the way the game interprets the accelerometer based on the orientation.

In iOS 5 I used the willRotateToInterfaceOrientation to catch changes and change my variables, but that's deprecated in iOS6. My existing code looks like this:

    if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)      
        rect = screenRect;

    else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
        rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width );
    GameEngine *engine = [GameEngine sharedEngine];
    if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        engine.orientation = -1;
    } else {
        engine.orientation = 1;
    }
}

I understand that the replacement is the viewWillLayoutSubviews method in the UIViewController class. I'm building this game in cocos2d 2.1 and there doesn't appear to be a UIViewController class in the demo project, so I'm not clear on how to incorporate it and how the code should look in order to make this work.


Solution

  • Listen for device orientation changes:

    [[NSNotificationCenter defaultCenter] 
           addObserver:self
              selector:@selector(deviceOrientationDidChangeNotification:) 
                  name:UIDeviceOrientationDidChangeNotification 
                object:nil];
    

    When notified, get the device orientation from UIDevice:

    - (void)deviceOrientationDidChangeNotification:(NSNotification*)note
    {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        switch (orientation)
        {
            // etc... 
        }
    }