Question

So I'm working on a side scrolling game using SpriteKit, when I hit the home button do something else and then return to my game, the game starts over from the start screen.

How can I keep my place in the game?

Thank you soooo much for your help!!!! :)

Was it helpful?

Solution

What you probably want to do is a combo of pausing the game and checking if the scene has been created already. When the app goes to the background you will want to use the pause method to pause your game. Then have it unpause when it comes back. Also when it comes back check if the scene has been created, if it has do NOT make another, as your app is doing.

To pause and un-pause the game you can keep a notification for that. I made mine in the view controller that holds the scene. In the viewDidLoad method add..

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];

Then for the selectors I use these methods.

- (void)willEnterForeground
{
SKView *skView = (SKView *)self.view;
skView.scene.paused = NO;
[[SKTAudio sharedInstance] resumeBackgroundMusic];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
}

- (void)willEnterBackground
{
SKView *skView = (SKView *)self.view;
skView.scene.paused = YES;
[[SKTAudio sharedInstance] pauseBackgroundMusic];
[[AVAudioSession sharedInstance] setActive:NO error:nil];
}

To make sure you don't re-make your scene, when you do make it, check if one is made already. By checking if the scene is nil. Something like..

if (!skView.scene) { make your scene here }

OTHER TIPS

You cannot keep the game running in it's current state in the background, as iOS will remove it from memory as soon as it is required. You can keep operations running in the background for a finite amount of time, as demonstrated by this question:

How to keep an iPhone app running on background fully operational

However, this is not very helpful to your case as well.

I would suggest saving your game's state in NSUserDefaults (items like current score, positions of various nodes, etc) in the App Delegate method -applicationWillTermiate:, and then read the values in the -applicationDidFinishLaunching: method, to check whether a game was being played previously.

Make sure you don't have the property "UIApplicationExitsOnSuspend" or "Application does not run in background" set to YES in your app's info.plist file. If so, your app would always terminate when going to background.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top