为分数制作增量计数器

时间:2013-10-18 13:20:20

标签: cocos2d-iphone

如何制作一个从零增加(经过)到两秒钟内得分的计数器?我计划用这个来显示游戏中弹出的最终得分。我真的不太确定如何解决这个问题。请帮忙。

2 个答案:

答案 0 :(得分:0)

以下是您可以根据给定值设置动画(使用调度程序)的代码:

float secs = 2.0f;
float deciSecond = 1 / 10;
newScore = 100;

currentScore = 0;
scoreInDeciSecond = (newScore / secs) * deciSecond;
[self schedule:@selector(counterAnimation) interval:deciSecond];

这就是你的方法处理动画的方式:

- (void)counterAnimation {
   currentScore += scoreInDeciSecond;
   if (currentScore >= newScore) {
      currentScore = newScore;
      [self unschedule:@selector(counterAnimation)];
   }
   scoreLabel.string = [NSString stringWithFormat:@"%d", currentScore];
}

答案 1 :(得分:0)

我个人不知道cocos2d以及它如何显示文本或使用计时器,但这里是如何使用纯iOS SDK。如果您了解cocos2d,转换它应该不会有问题。

- (void)viewDidLoad
{
    [super viewDidLoad];
    highScoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(100.0, 100.0, 200.0, 75.0)];
    [self displayHighScore];
}

-(void)displayHighScore {
    highScore = 140;
    currentValue = 0;

    NSString* currentString = [NSString stringWithFormat:@"%d", currentValue];
    [highScoreLabel setText:currentString];
    [self.view addSubview:highScoreLabel];

    int desiredSeconds = 2; //you said you want to accomplish this in 2 seconds
    [NSTimer scheduledTimerWithTimeInterval: (desiredSeconds/highScore) // this allow the updating within the 2 second range
                                     target: self
                                   selector: @selector(updateScore:)
                                   userInfo: nil
                                    repeats: YES];
}

-(void)updateScore:(NSTimer*)timer {
    currentValue++;

    NSString* currentString = [NSString stringWithFormat:@"%d", currentValue];
    [highScoreLabel setText:currentString];

    if (currentValue == highScore) {
        [timer invalidate]; //stop the timer because it hit the same value as high score
    }
}