Search code examples
iossprite-kitskscene

Can't unpause SKScene after adding a label


I can pause and unpause the SKScene with a pause button(SKSpriteNode) and a simple method.

-(void) pauseGame {

    SKView *view = (SKView *) self.view;

    if(!view.paused){
        view.paused = YES;

    }else{
        view.paused = NO;
        [pauseLabel removeFromParent];
    }    
}

And call it in the touchesBegan Method

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    // If game is paused allow the button to be touched
    if (isGamePaused == NO) {


        //if pause button touched, pause the game
        if (node == pauseButton) {

            [self pauseGame];

        }
    }
}

This way works fine. I can push the button to pause the game and push it again to unpause the game. However, I want to give the user a way to know the game is paused other then the screen be frozen, so I tried this:

I create this SKLabel.

-(void) addPauseLabel {

    // Creating label
    pauseLabel = [SKLabelNode labelNodeWithFontNamed:universalFont];
    pauseLabel.text = @"Game is Paused";
    pauseLabel.fontSize = 42;
    pauseLabel.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2 + 60);
    pauseLabel.zPosition = 6;

    [self addChild:pauseLabel];
}

Then I created a sequence in which I add the label then pause the game

-(void) pauseSequence{

    SKAction *pauseSequence = [SKAction sequence:@[
                                                   [SKAction performSelector:@selector(addPauseLabel) onTarget:self],
                                                   [SKAction performSelector:@selector(pauseGame) onTarget:self],
                                                   ]];
    [self runAction:pauseSequence];

}

And finally, in the touchesBegan method, I call [self pauseSquence]; at the end instead of [self pauseGame];

When I push the pause button the label is added and the game is pauseed, but pushing the button again to unpuase the game doesn't do anything. Why is that? Any help would be greatly appreciated. Thank you.


Solution

  • You can't run an action while the view is paused, so you should call [self pauseSequence] if the view is not paused and [self pauseGame] if the view is paused.

    In the touchesBegan method

    if (!self.view.paused) {
        // Add label and pause
        [self pauseSequence];
    }
    else {
        // Resume game
        [self pauseGame];
    }