Objective-C: 在 SpriteKit 中为计时器添加 10 秒

Objective-C: Adding 10 seconds to timer in SpriteKit

我使用别人的代码在 SpriteKit 中编写了一个计时器,并对其进行了一些调整。这是我的代码的样子:

- (void)createTimerWithDuration:(NSInteger)seconds position:(CGPoint)position andSize:(CGFloat)size
{
    // Allocate/initialize the label node.
    _countdownClock = [SKLabelNode labelNodeWithFontNamed:@"Avenir-Black"];
    _countdownClock.fontColor = [SKColor blackColor];
    _countdownClock.position = position;
    _countdownClock.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
    _countdownClock.fontSize = size;
    [self addChild:_countdownClock];

    // Initialize the countdown variable.
    _countdown = seconds;

    // Define the actions.
    SKAction *updateLabel = [SKAction runBlock:^{
        _countdownClock.text = [NSString stringWithFormat:@"Time Left: 0:%lu", (unsigned long)_countdown];
        _countdown--;
    }];

    SKAction *wait = [SKAction waitForDuration:1.0];

    // Create a combined action.
    SKAction *updateLabelAndWait = [SKAction sequence:@[updateLabel, wait]];

    // Run action "seconds" number of times and then set the label to indicate the countdown has ended.
    [self runAction:[SKAction repeatAction:updateLabelAndWait count:seconds] completion:^{
        _countdownClock.text = @"GAME OVER!";
        _gameOver = YES;
        [self runAction:_gameOverSound];
    }];
}

我想要发生的是,当某个代码块是 运行(我自己处理过)时,我想给计时器增加 10 秒。

我已经尝试这样做了,方法是添加一个名为 _countTime 的常量实例变量,最初保持 60 秒。在 -init 方法中,我调用了 [self createTimerWithDuration:_countTime position:_centerOfScreen andSize:24]; 在这个函数中,每次 "seconds" 减少时我都会减少 _countTime - 换句话说,每秒 _countTime会减少。当我有块 运行 时,块要向时间添加 10 秒,我会删除 _countdownClock,向 _countTime 添加 10 秒,最后调用 createTimerWithDuration:position:andSize:再次更新 _countTime.

但这似乎对我不起作用。我认为它会工作得很好。它 did 将时间增加了 10 秒,就像我想要的那样,但是计时器会开始减三秒。它会等一秒钟,然后是 15-14-12 BAM!然后等一下,然后是 11-10-9 BAM!等等。

这是怎么回事?这是正确的做法吗?我有没有更好的方法来增加时间,或者(更好!)更好的方法来创建一个计时器,它有一个功能像这样?

我认为问题是因为您是 运行 对 "self" 的操作。您的旧操作没有被删除,它仍在每秒删除时间。试试这个...

[_countdownClock runAction:[SKAction repeatAction:updateLabelAndWait count:seconds] completion:^{
    _countdownClock.text = @"GAME OVER!";
    _gameOver = YES;
    [self runAction:_gameOverSound];
}];

and finally call createTimerWithDuration:position:andSize:

我假设您在再次调用之前删除了旧标签,否则您会得到一些看起来非常奇怪的文本。当您从其父项中删除 _countdownClock 时,它也应该删除操作并且它不会继续减少时间并且应该解决您的问题。

希望对您有所帮助。