Stagger NSTimer

时间:2015-06-23 14:58:07

标签: swift timer sprite-kit

我有3种不同的NSTimers,我想每隔0.3秒发射一次,但我希望3个NSTimers交错,这样它们就不会同时发射。例如,NSTimer1在0.1时开始,然后在0.4时,NSTimer2在0.2时触发,然后在0.5时触发,NSTimer3在0.3时触发,然后在0.6时触发,然后触发1。

以下是我目前正在使用的内容,我不确定他们是否确实在同一时间开枪,我只是假设。任何建议将不胜感激。

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)

2 个答案:

答案 0 :(得分:1)

您可以使用块来完成此任务。

-(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;

答案 1 :(得分:1)

我建议您在Sprite Kit游戏中使用SKAction或者两个而不是NSTimer,因为当您暂停/恢复SKView和/或{{1时,操作会暂停/恢复}}。以下是如何使用SKScene s错开事件的示例:

SKAction