所以我遵循了LearnCocos2D的回答,但我做了一个小小的修改,我认为这很好。它适用于我的目的,所以我想把它放在那里。
我所做的是这样的:
//This is the boring bits for creating the SKSpriteNode
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];
// I added a timer with winkWaitingTime as interval. This is the variable
// to change. Set this to something at the beginning.
NSTimer *timered= [NSTimer scheduledTimerWithTimeInterval:winkWaitingTime target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
[timered fire];
}
-(void)timerFired:(NSTimer*)timer{
//In the NSTimer Selector, I set the timer interval/SKAction waiting interval to a random
// number
winkWaitingTime =[[SharedInfo sharedManager] randomFloatBetween:3 and:8];
[headsNode removeAllActions];
//I thought it's best to remove the actions JIC :)
[headsNode runAction:[self returnActionForAnimationKey:headsNode.name]];
NSLog(@"winktimer: %f",winkWaitingTime);
}
-(SKAction*)returnActionForAnimationKey:(NSString*)animationKey{
CGFloat waitDuration;
//This is for just to prevent timer fire interfering with the SKAction
//This will make the SKAction waiting time shorter than NSTimer Fire rate
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;
}
正如我所说的,我的作品,并通过改变winkWaitingTime,有点防范管理,它的工作原理。
我希望你觉得它也很有用。在内存管理方面,我的Xcode显示CPU /内存/电池使用量稳定,所以没有增加使用。
备注:收到评论后,我认为最好讨论使用NSTimer
。如果你需要做一些“外部”操作,即独立于视图或场景,那么我会使用NSTimer
(这是我的情况)。但是你必须为计时器实现暂停和取消暂停。 (您必须使NSTimer
无效才能停止,并重新安排新的时间,或将其作为变量并重新计划同一时间)。否则,请使用SKAction
,您不需要暂停和取消暂停NSTimer
。
你为什么在这里使用NSTimer?您可以始终使用与NSTimer使用SKAction相同的功能。区别在于NSTimer不受场景或视图的影响,甚至不受节点的暂停状态的影响,所以如果您没有为NSTimer实现自定义暂停功能,则可能会遇到问题。使用SKA自动停止/取消暂停。 – Whirlwind 2016-03-19 13:44:00
@Whirlwind是的,但对于我的项目,我想有一个“外部”定时器,做一些其他的事情(我没有在这里添加它,因为它是无关紧要的),并创建了一个暂停/非暂停方法好吧,更像是验证/无效)。我编辑了这个问题来反映这一点。 – Septronic 2016-03-19 13:57:39
啊,好吧,我只是觉得你不知道NSTimer在SpriteKit项目中的行为。 – Whirlwind 2016-03-19 15:14:44