【问题标题】:Objective-C: Adding 10 seconds to timer in SpriteKitObjective-C:在 SpriteKit 中为计时器添加 10 秒
【发布时间】:2015-09-30 10:09:22
【问题描述】:

我使用别人的代码在 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]; 在这个函数中,每次“秒”减少时,我都会减少 _countTime ——换句话说,每秒钟,_countTime 就会减少。当我让块运行时,将块添加 10 秒的时间,我会删除 _countdownClock,将 10 秒添加到 _countTime,最后再次调用 createTimerWithDuration:position:andSize:,更新 _countTime

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

那么这里发生了什么?这是正确的方法吗?有没有更好的方法来增加时间,或者(更好!)更好的方法来创建具有这样功能的计时器?

【问题讨论】:

    标签: objective-c time timer sprite-kit seconds


    【解决方案1】:

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

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

    最后调用 createTimerWithDuration:position:andSize:

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

    希望对您有所帮助。

    【讨论】:

    • 哇...我不敢相信我没想到!当然,在现场运行它会导致问题。回复晚了非常抱歉;有一段时间我没有机会工作。但它现在工作正常。我接受了这个答案!
    • @ChristianKRider 很高兴它成功了。那个错误会让我发疯:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多