0

Problem: I have a game which generates wall in every 2 seconds. When I press Home button, and then come back to my game, the pattern of wall creation is disrupted. My theory is that when the game is suspended via Home button, the game scene stops but the timer doesnt stop and continues to create the walls which causes the problem.

I tried to stop the timer of wall creation when the game is suspended:

WallGenerationTimer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self , selector: "generateWall", userInfo: nil, repeats: true) 

I checked several answers but all of them explains the solution when NSTimer sits in GameViewController and I cant access my NSTimer in GameScene from GameViewController. The answers are based on using to send notification from applicationWillResignActive and applicationDidEnterBackground functions in AppDelegate.swift file, then using an observer in GameViewController to stop the timer in it.

However, my timer is in GameScene and I couldnt figure out how to stop it when the game is suspended.

What I tried:

I tried to add an observer in GameScene inside the update function and I call a function when the notification is sent through applicationWillResignActive and applicationDidEnterBackground, this function stops timer by:

generationTimer?.invalidate()

this didnt work and the problem still exists.

johncoffey
  • 251
  • 3
  • 12

1 Answers1

0

Do not use NSTimer in SpriteKit. Use SKAction instead as all SKActions are automatically paused when the app is no longer active. For example, you could use:

(SKAction *)performSelector:(SEL)selector onTarget:(id)target

with

(SKAction *)waitForDuration:(NSTimeInterval)sec

and run them in a sequence once

[self runAction:[SKAction sequence:@[action0, action1]]];

or forever

SKAction *myActionSequence = [SKAction sequence:@[action0, action1]];
[self runAction:[SKAction repeatActionForever:myActionSequence]];
sangony
  • 11,636
  • 4
  • 39
  • 55
  • very interesting! thanks for the response. i am not very familiar with objective c. any chance for you to share this code's swift version? – johncoffey Apr 05 '15 at 15:50
  • @johncoffey - Sorry, I'm not yet versed in swift but you can get the swift equivalents from the Apple SKAction docs here https://developer.apple.com/library/prerelease/ios/documentation/SpriteKit/Reference/SKAction_Ref/index.html – sangony Apr 05 '15 at 17:17
  • thanks though. i actually checked it further and i found this article: http://stackoverflow.com/questions/24170282/swift-performselector-withobject-afterdelay. They seem to recommend nstimer as a solution for performing selector. i get your point and it might be better in my case but instead of trying to move my wall creation flow to a new method, i would prefer to stop nstimer through the notification from appdelegate. – johncoffey Apr 05 '15 at 17:49