【发布时间】: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