我用別人的代碼在SpriteKit中寫入了一個定時器,並稍微調整了一下。這裏是我的代碼如下所示:Objective-C:在SpriteKit中爲定時器添加10秒
- (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!等等。
那麼這裏發生了什麼?這是正確的做法嗎?有沒有更好的方法來增加時間,或者(更好!)創建一個定時器的更好的方法,它有這樣的功能?
哇......我簡直不敢相信我沒有想到!當然,在現場運行會產生問題。回覆晚了非常抱歉;我有一段時間沒有機會開展工作。但現在它工作正常。我接受了這個答案! –
@ChristianKRider很高興它的工作。該錯誤會驅使我瘋了:) –
「會有_driven_我堅果」......大聲笑! –