So I followed LearnCocos2D's answer, but I made a slight modification, which I think works great. It works for my purpose, so I thought to put it out there.
What I did was this:
headsNode = [SKSpriteNode spriteNodeWithTexture:[self.textureAtlas firstObject]size:CGSizeMake(100, 100)];
headsNode.position = CGPointMake(CGRectGetMidX(self.frame)*0.5, CGRectGetMidY(self.frame)-coinSize/2);
headsNode.name = @"Heads";
[self addChild:headsNode];
NSTimer *timered= [NSTimer scheduledTimerWithTimeInterval:winkWaitingTime target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
[timered fire];
}
-(void)timerFired:(NSTimer*)timer{
winkWaitingTime =[[SharedInfo sharedManager] randomFloatBetween:3 and:8];
[headsNode removeAllActions];
[headsNode runAction:[self returnActionForAnimationKey:headsNode.name]];
NSLog(@"winktimer: %f",winkWaitingTime);
}
-(SKAction*)returnActionForAnimationKey:(NSString*)animationKey{
CGFloat waitDuration;
if (winkWaitingTime >4) {
waitDuration = winkWaitingTime-3;
}else{
waitDuration = 1;
}
SKAction *sequence = [SKAction sequence:@[
[SKAction waitForDuration:waitDuration],
[SKAction animateWithTextures:self.textureAtlas timePerFrame:0.1f resize:NO restore:YES]]];
return sequence;
}
As I said, it works for me, and by changing the winkWaitingTime, and a bit of prevention management, it works.
I hope you find it useful as well. In terms of memory management, my Xcode is showing stable CPU / Memory / Battery usage, so there's no increase in use.
NOTE: After receiving a comment, I thought it's best to discuss the use of NSTimer
. If you need to have something done "externally", i.e. independent to the view or scene, then I'd use the NSTimer
(that was my case). But you'd have to implement the pausing and unpausing for the timer as well. (You'd have to invalidate the NSTimer
to stop, and reschedule a new one, or have it as a variable and reschedule the same one). Otherwise, use the SKAction
and you won't need to pause and unpause the NSTimer
.