Reputation: 313
Is there any way to add a delay of a fraction of a second to a loop (e.g. A for loop). i.e. I would like a short delay after each iteration.
I know that cocos2d allows you to schedule selecters with a delay. But I am not sure how this could be used in this case.
I also know that sleep is costly and not advisable.
Any suggestions?
Upvotes: 1
Views: 2605
Reputation: 10860
You should not use NSTimers in cocos2d. It will cause troubles if you want to have possibility to pause your game.
If you want to loop some action with fixed delay between iterations, you can freely use scedule:interval: method with needed delay.
[self schedule:@selector(methodToScedule) interval:yourDelay]
Or if you have to do random delay, you can use sequenses of cocos2d actions. For example
- (void) sceduleMethod
{
// do anything you want
ccTime randomDuration = // make your random duration
id delayAction = [CCDelayTime actionWithDuration: randomDuration];
id callbackAction = [CCCallFunc actionWithTarget:self selector:@selector(scheduleMethod)];
id sequence = [CCSequenece actionOne: delayAction actionTwo: callbackAction];
[self runAction: sequence];
}
in this case you must call your method only once. Then it will call itself with given delay.
Upvotes: 2
Reputation: 6679
You could use C's sleep function:
sleep(seconds);
But you could also look at UITimer
, or possibly a block-based performSelector:withObject:afterDelay:
method.
See this for more NSObject-based methods: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelector:withObject:afterDelay
Upvotes: 0