SpriteKit Pause and Resume SKView

I want to pause and shutdown a scene in SpriteKit using 2 buttons in one position. While the scene is running, I want to show the Pause button. While the scene is paused, I want to hide the Pause button and show the Play button. In SpriteKit you can use self.scene.view.paused

which is defined in SpriteKit.

My code:

@implementation MyScene {

SKSpriteNode *PauseButton;
SKSpriteNode *PlayButton;

}

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {

[self Pause];

}
return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */

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

SKNode * Node = [self nodeAtPoint:location];

if([Node.name isEqualToString:@"PauseButton"]){

    self.scene.view.paused = YES;

    [PauseButton removeFromParent];
    [self Resume];
}

if([Node.name isEqualToString:@"PlayButton"]){

    self.scene.view.paused = NO;

    [PlayButton removeFromParent];
    [self Pause];
}
}

-(void)Pause{

PauseButton = [SKSpriteNode spriteNodeWithImageNamed:@"Pause.png"];
PauseButton.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 1.04);
PauseButton.zPosition = 3;
PauseButton.size = CGSizeMake(40, 40);
PauseButton.name = @"PauseButton";

[self addChild:PauseButton];

}

-(void)Resume{

PlayButton = [SKSpriteNode spriteNodeWithImageNamed:@"Play.png"];
PlayButton.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 1.04);
PlayButton.zPosition = 3;
PlayButton.size = CGSizeMake(60, 60);
PlayButton.name = @"PlayButton";
[self addChild:PlayButton];

}

      

It pauses the scene, but there is a Pause button, and if I touch the Pause button again, the Scene will resume. Therefore, now only the images will not change. How can I fix this?

+2


source to share


1 answer


You cannot update the button (or anything else in the scene) while the SKView is paused. In your method, touchesBegan

you pause the view before refreshing the button (reordering won't work). You will need to go back into a run loop for your button to be updated before the game is paused. Here's one way to do it:

This calls the pause method after a short delay. Add this after your statement [self Resume]

in touchesBegan

and remove self.scene.view.paused = YES

.

    [self performSelector:@selector(pauseGame) withObject:nil afterDelay:1/60.0];

      



This method pauses the SKView. Add this to your MyScene.m

- (void) pauseGame
{
    self.scene.view.paused = YES;
}

      

+5


source







All Articles