Incremenent NSnumber every 5 seconds - Cocos2d

2019-08-09 19:39发布

问题:

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);   

}

回答1:

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.



回答2:

I think method [self schedule:@selector(methodName) interval:intervalValue]; is your choice.

Code sample:

```

static CGFloat playTime = 0.0;
@implementation GameScene {

}

-(void)onEnter
{
    CCLOG(@"on enter");
    [self schedule:@selector(runTimer) interval:5.0];
    [super onEnter];
}

-(void) runTimer {
    playTime += 1;
}

```