我有3种不同的NSTimers,我想每0.3秒钟触发一次,但我希望3 NSTimers被交错,这样它们就不会同时开火。例如,NSTimer1火灾在0.1,然后在0.4,NSTimer2火灾在0.2,然后在0.5,NSTimer3火灾在0.3,然后在0.6,等等。
下面是我目前正在使用的东西,我不确定它们是否真的同时发射,我只是假设。如有任何建议,将不胜感激。
var timer1 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment1"), userInfo: nil, repeats: true)
var timer2 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment2"), userInfo: nil, repeats: true)
var timer3 = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector("updateSegment3"), userInfo: nil, repeats: true)发布于 2015-06-23 15:30:28
您可以使用块来完成这一任务。
-(void)didMoveToView:(SKView *)view {
SKAction *wait0 = [SKAction waitForDuration:0.1];
SKAction *block0 = [SKAction runBlock:^{
// run first timer code
}];
[self runAction:[SKAction sequence:@[wait0, block0]]];
SKAction *wait1 = [SKAction waitForDuration:0.2];
SKAction *block1 = [SKAction runBlock:^{
// run second timer code
}];
[self runAction:[SKAction sequence:@[wait1, block1]]];
SKAction *wait2 = [SKAction waitForDuration:0.3];
SKAction *block2 = [SKAction runBlock:^{
// run third timer code
}];
[self runAction:[SKAction sequence:@[wait2, block2]]];
}如果你想使用调度,试试下面的代码.
为计时器创建一个属性:
@property (nonatomic, strong) dispatch_source_t myTimer;接下来,创建定时器:
// Get the queue to run the blocks on
dispatch_queue_t queue = dispatch_get_main_queue();
// Create a dispatch source, and make it into a timer that goes off every second
self.myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.myTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0);
// When the timer goes off, run your code
dispatch_source_set_event_handler(self.myTimer, ^{
//code...
});
// Dispatch sources start out paused, so start the timer by resuming it
dispatch_resume(self.myTimer);
// To cancel the timer, just set the timer variable to nil:
self.myTimer = nil;发布于 2015-06-23 18:37:35
我建议您在雪碧套件游戏中使用一两个SKAction而不是NSTimer,因为当您暂停/恢复SKView和/或SKScene时,动作会暂停/恢复。下面是一个如何使用SKActions错开事件的示例:
override func didMoveToView(view:SKView) {
let wait = SKAction.waitForDuration(0.1)
let block1 = SKAction.runBlock({
updateSegment1()
})
let block2 = SKAction.runBlock({
updateSegment2()
})
let block3 = SKAction.runBlock({
updateSegment3()
})
let sequence = SKAction.sequence([wait,block1,wait,block2,wait,block3])
self.runAction(SKAction.repeatActionForever(sequence), withKey:"timer")
// Use the following to terminate the timer
//self.removeActionForKey("timer")
}https://stackoverflow.com/questions/31006331
复制相似问题