What is causing my SKAction timer to behave strangely?

纵然是瞬间 提交于 2019-12-06 04:19:16

I have tried the below code and it works. The spawning stops when the app resigns active and starts itself again once the app becomes active again.

You do not need to manually include code to pause as SpriteKit will pause itself when resigning active but I included it to show how to communicate between the AppDelegate and SKScene.

AppDelegate.m

- (void)applicationWillResignActive:(UIApplication *)application {
[[NSNotificationCenter defaultCenter]postNotificationName:@"applicationWillResignActive" object:self];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
[[NSNotificationCenter defaultCenter]postNotificationName:@"applicationDidBecomeActive" object:self];
}

GameScene.m

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
    SKAction *wait = [SKAction waitForDuration:1.5];
    SKAction *run = [SKAction performSelector:@selector(spawningEnemy) onTarget:self];
    SKAction *spawnAction = [SKAction repeatActionForever:[SKAction sequence:@[wait,run]]];
    [self runAction:spawnAction withKey:@"spawn"];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(pauseGame)
                                                 name:@"applicationWillResignActive"
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(resumeGame)
                                                 name:@"applicationDidBecomeActive"
                                               object:nil];
    }
return self;
}

-(void)spawningEnemy {
    NSLog(@"spawningEnemy");
}

-(void)pauseGame {
    NSLog(@"applicationWillResignActive...");
    self.paused = YES;
}

-(void)resumeGame {
    NSLog(@"applicationDidBecomeActive...");
    self.paused = NO;
}

-(void)willMoveFromView:(SKView *)view {
// good housekeeping
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
Thomm

If it is the whole scene that you want to have paused, then you should only pause the SKView containing the scene. This will pause all animations, run loops and interaction of the scene and all nodes within the scene.

Also experience learned me that it is good practice to pause the scene when the application goes to the background and resume when it returnes to the foreground. It prevents issues such as: Sprite Kit & playing sound leads to app termination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!