0

I am trying to remove a SKScene and add a new one. The first presentScene: works fine, but the second one has messed up bounds, like this.

Here is my code.

@implementation GameViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadLevel:1];
}

- (void)loadLevel:(int)level {
    SKView * skView = (SKView *)self.view;
    [skView presentScene:nil];

    GameScene * gameScene;
    switch (level) {
        case 1:
            gameScene = [Level1 sceneWithSize:skView.bounds.size];
            break;

        case 2:
            gameScene = [Level2 sceneWithSize:skView.bounds.size];
            break;

        default:
            break;
    }
    gameScene.scaleMode = SKSceneScaleModeAspectFill;
    gameScene.gameViewController = self;
    self.gameScene = gameScene;
    [skView presentScene:gameScene transition:[SKTransition crossFadeWithDuration:1.0f]];
}

2 Answers 2

0

I didn't figure out why skView.bounds.size was changing between levels, but to correct it I hardcoded the size in. Let me know if there's a better way of doing it.

gameScene = [Level1 sceneWithSize:CGSizeMake(768, 1024)];
0

You run this in viewDidLoad, which means the view will be in portrait mode at that time:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadLevel:1];
}

To fix this, you should present the first scene in viewWillLayoutSubviews:

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if (((SKView*)self.view).scene == nil)
    {
        [self loadLevel:1];
    }
}

It's important to add the nil check because viewWillLayoutSubviews will be called repeatedly, for instance when rotating the device.

2
  • [self loadLevel:1] is fine, it's when Level1 calls [self.gameViewController loadLevel:2] that the weird bounds happen.
    – felix2018
    Oct 22, 2014 at 14:39
  • Yes, because in the first scene you may get 1024x768 as the size, and the next time it's 768x1024. Give it a try, I wouldn't be surprised if that fixes things. Or both scene may be broken after making this change, which would indicate the scene's scaleMode is not set to the desired scale mode.
    – CodeSmile
    Oct 22, 2014 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.