我使用其他人的代码在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,最后使用更新的_countTime再次调用createTimerWithDuration:position:andSize:。
但这似乎不适合我。我觉得会很好的。给时间增加了10秒,和我想要的完全一样,但是计时器开始下降3秒。它会等一秒钟,然后15-14-12 BAM!然后等一下,然后是11-10-9 BAM!诸若此类。
这是怎么回事?这是正确的方法吗?是否有更好的方法来增加时间,或者(更好地!)一个更好的方法来创建一个具有这样一个功能的计时器?
发布于 2015-07-12 09:48:16
我相信问题是因为你在“自我”上运行。你以前的动作没有被移除,它仍然是每秒钟都在消耗时间。试试这个..。
[_countdownClock runAction:[SKAction repeatAction:updateLabelAndWait count:seconds] completion:^{
_countdownClock.text = @"GAME OVER!";
_gameOver = YES;
[self runAction:_gameOverSound];
}];最后,调用createTimerWithDuration:andSize:andSize:
在再次调用之前,我假设您正在删除旧标签,否则您将得到一些非常奇怪的文本。当您从它的父级中删除_countdownClock时,它也应该删除该操作,它不会一直减少时间,应该修复您的问题。
希望这能帮上忙。
https://stackoverflow.com/questions/31361442
复制相似问题