Search code examples
ioscocos2d-iphonensnumber

Incremenent NSnumber every 5 seconds - Cocos2d


I am trying to increment a NSNumber every 5 seconds by 1 in Cocos2d but for some reason it isn't working (probably obvious mistake). I am using the update method but I think this may be the wrong place. Currently it is only adding +1 once. I need it to do this every 5 seconds constantly:

-(void) update: (CCTime) delta
{
    // Save a string:
    NSNumber *anInt = [NSNumber numberWithInt:500];

    NSNumber *bNumber = [NSNumber numberWithInt:[anInt intValue] + 1];

    NSLog(@"Update Number%@",bNumber);   

}

Solution

  • An easy way to run something every 5 seconds would be to:

    Create a property storing your number and a timer:

    @property (nonatomic, assign) int bNumber;
    @property (nonatomic, strong) NSTimer* timer;
    

    Then initialize the number to 500 (I assume based on your example you want it to start at 500) and create the timer:

    - (instanceType)init
    {
        self = [super init];
    
        if (self)
        {
            self.bNumber = 500;
    
            self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0f
                                                  target:self
                                                selector:@selector(incrementScore:)
                                                userInfo:nil
                                                 repeats:YES];
        }
    }
    

    Then create a method that does the increment:

    - (void)incrementScore:(NSTimer *)timer
    {
        self.bNumber++;
        NSLog(@"Number = %d", self.bNumber);
    }
    

    Don't forget to invalidate the timer when you are done:

    - (void)dealloc
    {
        // If not using arc don't forget super dealloc
        [super dealloc];
    
        [self.timer invalidate];
        self.timer = nil;
    }
    

    That is one way. If you want to use the update method in cocos2d then you need to be keeping track of the accumulated delta. Once that value has reached or exceeded the total number of milliseconds in 5 seconds, then you add 1 to the number. Delta is the number of milliseconds that have passed since the last update. So for example the properties will be:

    @property (nonatomic, assign) int bNumber;
    @property (nonatomic, assign) CCTime totalDelta;
    

    Then in update you would do the following (there are 1000 milliseconds in a second):

    - (void)update:(CCTime)delta
    {
        const CCTime FiveSeconds = 5000.0f;
        self.totalDelta += delta;
    
        if (self.totalDelta >= FiveSeconds)
        {
            self.totalDelta = 0;
            self.bNumber++;
    
            NSLog(@"Number = %d", self.bNumber);
        }
    }
    

    I hope this helped. What you are trying to do is pretty simply so I recommend brushing up on Obj-C programming before jumping into making games.