我有一个游戏,当按下主页按钮时我已经成功实现了暂停功能。在具有主场景的View Controller中,我暂停使用:
- (void)appWillEnterBackground{
SKView *skView = (SKView *)self.view;
skView.paused = YES;
bubbleOn=NO; //turns bubble spawn off
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(appWillEnterForeground)
name:UIApplicationDidBecomeActiveNotification
object:NULL];
}
要取消暂停,
- (void)appWillEnterForeground{
SKView * skView = (SKView *)self.view;
skView.paused=NO;
bubbleOn=YES; Allows recursive method to run until bubbleOn = YES
[NSTimer scheduledTimerWithTimeInterval:slowMo target:scene selector:@selector(spawnNew) userInfo:nil repeats:NO]; //Recursive spawn method
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(appWillEnterBackground)
name:UIApplicationWillResignActiveNotification
object:NULL];}
这很有效,直到我的游戏结束并呈现新的场景(结束场景)。在结束场景显示得分之后,用户可以再次点击以再次开始并且呈现主场景。主场景的 initWithSize 方法开始递归方法 spawnNew 。如果应用程序进入后台,场景会暂停并生成新的停止。
但是当应用程序转到前台时,场景会恢复,但 spawnNew 方法不起作用。它被调用并输出正确的NSLog消息,但该方法不会产生气泡节点。
spawnNew方法在我的主场景的实现中:
-(void) spawnNew{
if (bubbleOn==YES){
bubble = [SKSpriteNode spriteNodeWithImageNamed:ballName];
bubble.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:bubble.size.width/2];
...
//bubble properties
...
[self addChild:bubble];
NSLog(@"Spawn!");
[NSTimer scheduledTimerWithTimeInterval:slowMo target:self selector:@selector(spawnNew) userInfo:nil repeats:NO];
return;
} else{
return;
}
此时我没有想法!有什么建议?
答案 0 :(得分:3)
最简单的方法是摆脱NSTimer
。您可以改为使用SKAction
。
使用SKScene
initWithSize
方法:
- (instancetype)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
....
__weak GameScene *weakSelf = self;
SKAction *spawnBubble = [SKAction runBlock:^{
[weakSelf spawnNew];
}];
SKAction *wait = [SKAction waitForDuration:slowMo];
[self runAction:[SKAction repeatActionForever:
[SKAction sequence:@[spawnBubble,wait]]]];
}
return self;
}
在这种情况下,您甚至不需要使用bubbleOn
变量,因为一旦SKView
暂停,场景就会停止执行任何操作。