Search code examples
ioscocos2d-iphone

Lock App into one specific orientation in Cocos2D v3


I am trying to disable screen rotation in cocos2d-3.x, but I cannot figure out how. I have the following code in CCAppDelegate:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

 setupCocos2dWithOptions:

    [self setupCocos2dWithOptions:@{

        CCSetupShowDebugStats: @(YES),
        // Run in portrait mode.
        CCSetupScreenOrientation: CCScreenOrientationPortrait,

    }];

    return YES;
}

The screen is in portrait mode, but it also rotates to portrait UpsideDown. I read that Cocos2d uses a UIViewController so should I use an apple method for this?


Solution

  • Cocos2D currently only allows to choose between "Landscape" or "Portrait" but doesn't allow to specify the orientation more specific. This likely will be fixed in Cocos2D but for now you can modify the Cocos2D source code as a workaround. I have opened a GitHub Issue for this problem.

    Implementing supportedInterfaceOrientations in CCAppDelegate does not fix the issue because the method is implemented by the CCNavigationController and that overrides your settings.

    Open "CCAppDelegate.m" and go to line 77. You should see this method:

    -(NSUInteger)supportedInterfaceOrientations
    {
        if ([_screenOrientation isEqual:CCScreenOrientationAll])
        {
            return UIInterfaceOrientationMaskAll;
        }
        else if ([_screenOrientation isEqual:CCScreenOrientationPortrait])
        {
            return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
        }
        else
        {
            return UIInterfaceOrientationMaskLandscape;
        }
    }
    

    You can change the entire method to only support one orientation, e.g.:

    -(NSUInteger)supportedInterfaceOrientations
    {
        return UIInterfaceOrientationPortrait;
    }
    

    When you change that method you can return one of the 4 orientations you want to lock your game into:

    UIInterfaceOrientationMaskLandscapeLeft
    UIInterfaceOrientationMaskLandscapeRight
    UIInterfaceOrientationMaskPortrait
    UIInterfaceOrientationMaskPortraitUpsideDown
    

    That's the workaround for now.