我使用了别人的代码在 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
.
但这似乎对我不起作用。我认为它会运作得相当好。它did时间增加了 10 秒,就像我想要的那样,但计时器会开始减少 3 秒。稍等一下,然后 15-14-12 BAM!然后等一下,然后是 11-10-9 BAM!等等。
那么这是怎么回事呢?这是正确的方法吗?有没有更好的方法让我增加时间,或者(更好了!)有更好的方法来创建一个具有这样的功能的计时器吗?
我认为问题是因为您正在“自我”上执行操作。您的旧操作不会被删除,并且仍然每秒都会删除时间。尝试这个...
[_countdownClock runAction:[SKAction repeatAction:updateLabelAndWait count:seconds] completion:^{
_countdownClock.text = @"GAME OVER!";
_gameOver = YES;
[self runAction:_gameOverSound];
}];
最后调用 createTimer WithDuration:position:and Size:
我假设您在再次调用之前删除了旧标签,否则您会得到一些看起来非常奇怪的文本。当您删除时_countdownClock
从其父级开始,它还应该删除该操作,并且不会继续减少时间并且应该解决您的问题。
希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)