tags:

views:

96

answers:

2

Hello,
I'm making a game on iPhone using cocos2d, and I have a question.
In my init method I'm doing this :

[self schedule:@selector(newMonster:) interval:1];   

It create a new monster every second.
But I'd like that the interval change over time. For example :

  • The 10 first seconds of the game: a new monster appears every 1 second.
  • Then for 10 seconds: a new monster appears every 0.8 second.
  • And after every 0.5 second...

How can I do that?

Thanks !

A: 

Make an instance variable and property of NSDate called monsterSpawnStartDate, make it an retaining property and synthesize it.
As soon as your first monster should be created, set it:

self.monsterSpawnStartDate = [NSDate date]; // Current date and time

And replace your code by this:

[self schedule:@selector(adjustMonsterSpawnRate) interval:0.1]; // Seems like you want it to fire every 0.1 seconds

Implement adjustMonsterSpawnRate like this:

- (void)adjustMonsterSpawnRate {
    NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:monsterSpawnStartDate];
    if (((seconds <= 10.0) && (seconds % 1.0)) || ((seconds <= 20.0) && (seconds % 0.8)) ((seconds > 20.0) && (seconds % 0.5)))
        [self newMonster]; // Let a new monster spawn
}
bddckr
A: 

You may try this- (I have copied some code from @bddckr)

Initial time:

self.monsterSpawnStartDate = [NSDate date];
self.lastTimeScheduledBefore = 0;//new var

Scheduled Method to create monster

- (void)scheduledMethod {
    NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:monsterSpawnStartDate];

    [self newMonster]; // Let a new monster spawn
    if (seconds >= 20.0  && lastTimeScheduledBefore == 10){
      [self unschedule:@(scheduledMethod)];
      [self unschedule:@(scheduledMethod) interval:0.5];
      lastTimeScheduledBefore = 20;
    }
    else if (seconds >= 10.0 && lastTimeScheduledBefore == 0){
      [self unschedule:@(scheduledMethod)];
      [self unschedule:@(scheduledMethod) interval:0.8]
      lastTimeScheduledBefore = 10;
    }
}

You can modify it as your need. You can use mod if it goes through a cycle.

Sadat