2015-07-11 23 views
4

我用別人的代碼在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!等等。

那麼這裏發生了什麼?這是正確的做法嗎?有沒有更好的方法來增加時間,或者(更好!)創建一個定時器的更好的方法,它有這樣的功能?

回答

2

我相信這個問題是因爲你正在對「自我」進行操作。您的舊操作沒有被刪除,並且仍然每秒都會刪除時間。試試這個...

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

最後調用createTimerWithDuration:位置:andSize:

我假設你要刪除的舊標籤,你叫一遍,否則你會得到一些非常奇怪的看着面前文本。當您從其父母中刪除_countdownClock時,它也應該刪除該操作,並且它不會持續減少時間並應修復您的問題。

希望有幫助。

+0

哇......我簡直不敢相信我沒有想到!當然,在現場運行會產生問題。回覆晚了非常抱歉;我有一段時間沒有機會開展工作。但現在它工作正常。我接受了這個答案! –

+0

@ChristianKRider很高興它的工作。該錯誤會驅使我瘋了:) –

+0

「會有_driven_我堅果」......大聲笑! –