Search code examples
objective-cioscocoa-touchgamekit

iOS: Fire method at gradually increasing speed


My game plays a ticking clock sound every second. I would like the sound to slowly speed up throughout the game. My initial thought was to use an NSTimer and update the speed when the method fires, like this:

static float soundDelay = 1.0;
timer = [NSTimer scheduledTimerWithTimeInterval:clickClackDelay
                                                     target:self
                                                   selector:@selector(playSound)
                                                   userInfo:nil
                                                    repeats:YES];

- (void)playSound {
    soundDelay -= 0.1;
    NSLog(@"Play sound");
}

This didn't work, and it seems like NSTimer isn't really meant to be used that way. Any other suggestions on how I could accomplish this?


Solution

  • You can implement it by calling the playSound method from itself. You can do it in the following way.

    - (void)playSound
    {
       static float soundDelay = 1.0;
       if([timer isValid])
       {
         [timer invalidate];
         timer = nil;
       }
       timer = [NSTimer scheduledTimerWithTimeInterval:clickClackDelay
                                                         target:self
                                                       selector:@selector(playSound)
                                                       userInfo:nil
                                                        repeats:NO];
        soundDelay -= 0.1;
        if(soundDelay <=0)   //when sound delay is zero invalidate timer
        {
           [timer invalidate];
           timer = nil;
        }
        NSLog(@"Play sound");
    }