John Dorsey John Dorsey - 22 days ago 7
iOS Question

Setting screen orientation from inside SKScene

My game is implemented in a single SKScene object. A button (SKSpriteNode) lets the user switch from landscape to portrait mode. Well, it should. But I can't make this work. There are many discussions on this but they are all rather complicated and give suggestions that are completely different.

So.... What is the easiest way to make a button in an SKScene that changes the orientation to portrait or landscape?

Any suggestions are appreciated.

Answer

Here is a short, concise, complete answer to the question I posted.

  1. In xcode, select File->New->Project->IOS->Application->Game to generate a default app framework for a game for IPad using SpriteKit with ObjectiveC. This is the classic HelloWorldApp where spinning airplanes appear whenever you touch the screen.

  2. In Targets->DEploymentInfo->DeviceOrientation, checkmark Portrait and LandscapeLeft

  3. Modify shouldAutorotate for the view controller like so...

    - (BOOL)shouldAutorotate
    {
        int currentOrientation = (int)[[UIDevice currentDevice] orientation];
        if (scene.orientation != currentOrientation) {
            // Rotate the device back to orginial orientation
            [[UIDevice currentDevice] setValue:
             [NSNumber numberWithInteger: scene.orientation]
                                        forKey:@"orientation"];
            return NO;
        }
        return YES;
    }
    
  4. change the body of touchesBegan in your gameScene class like so...

    -(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
          /* Called when a touch begins */
            NSLog(@"%d", self.orientation);
            if (!self.orientation ||  self.orientation == UIInterfaceOrientationPortrait) {
                self.orientation = UIInterfaceOrientationLandscapeLeft;
            } else {
                self.orientation = UIInterfaceOrientationPortrait;
            }
            [[UIDevice currentDevice] setValue:
             [NSNumber numberWithInteger: self.orientation]
                                        forKey:@"orientation"];
    

the app will then hange orientation on each tap.