iphoneobjective-cmethodssparrow-framework

Objective-c -> iphone design: delayed action


Sorry to bother, but I am in a bit of a pickle and I was wondering if anyone here could give me a hand.

I am currently designing a game in which enemies appear on the left side of the screen (out of boundaries) and move to the right. I have used a number of codes (this is using Sparrow Framework) and pretty much the number of enemies increases as you beat them. i.e. lvl 1-> 1 enemy, lvl 2-> 2 enemies, lvl3-> 3 enemies, etc...

I am having some trouble though with producing enemies. I have them appearing on 1 of 5 set paths (path numbers in NSMutableArray), selected by a random number generator, however they often appear on the same path, 1 on top of the other.

To produce the enemies, i am running a number of methods: addEnemy -> produces the enemies (animations) which then travel from left to right. onTouchEnemy -> if i touch the enemy, they die. activates drawEnemies drawEnemies -> calls addEnemy a number of times equal to your lvl. coded as:

for(int i = 0; i < level; i++){
  [self performSelector:@selector(addEnemy) withObject:nil afterDelay:3.0];
}

Is there a way to program so that there is a delay between activating the produce enemies method? I tried this afterDelay, but for some reason the program just ignores the 3 second delay and just produces enemies all in 1 go. This is rather irritating since i would like them to appear in a more orderly fashion.

I thank anyone willing to give me a hand with this. Sjkato.


Solution

  • performSelector:withObject:afterDelay: appears to ignore its delay because of the way the code executes. That for loop will iterate almost instantly, queuing up 3 calls to the addEnemy method. After 3 seconds the addEnemy methods execute, almost all at the same time.

    To get a better result, you should look at NSTimer. You could set an interval of 3 seconds and tell it to repeat (you can invalidate the timer after the desired number of enemies has been produced).

    Something like:

    // creates and returns a new timer
    // the timer is retained by the run loop for as long as it is valid
    // invalidating the timer will cause the runloop to release it.
    myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                     target:self
                                   selector:@selector(addEnemy)
                                   userInfo:nil
                                    repeats:YES];
    

    This will cause the addEnemy method to be fired once every 3 seconds. You should keep a tally of how many enemies you have already made, and after the last one is made, stop the timer so that it doesn't fire again.

    if (numberOfDesiredEnemies == numberOfEnemiesProduced)
    {
        [myTimer invalidate], timer = nil;
    }