Pause Game
Pause Game
Use paused property in SKView.
Pause means that any actions, any physics, any events stop, We can stop game temporary.
Following code works in Scene
self.scene.view.paused = YES;
With button
We don’t have button UI in Sprite Kit.
Button UI and delegate
Create delegate to communicate with parent Scene.
Handle touch event in button node and call parent method using delegate
PauseButtonDelegate.h
@protocol PauseButtonDelegate <NSObject> - (void)pauseGame; @end
PauseButton.h
This class extends SKSpriteNode
@interface PauseButton : SKSpriteNode @property (nonatomic, weak)id<PauseButtonDelegate> pauseDelegate; - (instancetype)initWithSize:(CGSize)size; @end
PauseButton.m
#import "PauseButton.h" @implementation PauseButton - (instancetype)initWithSize:(CGSize)size { if(self = [super initWithColor:[UIColor orangeColor] size:size]) { self.userInteractionEnabled = YES; } return self; } #pragma mark - Touch Event Override - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Pause game if (self.pauseDelegate != nil) { [self.pauseDelegate pauseGame]; } } @end
Toggle operation in Scene
- (void)pauseGame { self.scene.view.paused = !self.scene.view.paused; }
And add PauseButton in scene(call in initWithSize)
PauseButton *button = [[PauseButton alloc] initWithSize:CGSizeMake(40, 40)]; button.position = CGPointMake(self.frame.size.width - 40, 25); button.pauseDelegate = self; [self addChild:button];