2014-04-30 39 views
4

我想出瞭如何在單視圖應用程序中創建定時器,但不是Spritekit。當我使用下面的代碼時,我得到2個錯誤(下面列出)。任何人都可以幫我解決這個問題嗎?謝謝,傑克。如何在Spritekit中創建一個計時器?

計時器。

if(!_scorelabel) { 
    _scorelabel = [SKLabelNode labelNodeWithFontNamed:@"Courier-Bold"]; 

    _scorelabel.fontSize = 200; 
    _scorelabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); 
    _scorelabel.fontColor = [SKColor colorWithHue: 0 saturation: 0 brightness: 1 alpha: .5]; 
    [self addChild:_scorelabel]; 
} 
_scorelabel = [NSTimer scheduledTimerWithTimeInterval: 1 target:self selector:@selector(Timercount)userInfo: nil repeats: YES]; 

的錯誤

Incompatible pointer types assigned to 'SKLabelNode*' from 'NSTimer*' 
Undeclared selector 'Timercount' 
+0

不使用NSTimer!請參閱:http://stackoverflow.com/a/23978854/201863 – LearnCocos2D

回答

0

您分配NSTimer你的SKLabelNode創建。要解決你的第一個錯誤,更改最後一行:

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(Timercount) userInfo:nil repeats:YES]; 

因爲你設置定時器呼叫被叫Timercount方法你所得到的第二個錯誤,但你沒有一個。

+3

NSTimer的另一種選擇是使用SKActions。 SKAction * wait = [SKAction waitForDuration:1.0f]; SKAction * sequence = [SKAction sequence:@ [[SKAction performSelector:@selector(method :) onTarget:self],wait]]; SKAction * repeat = [SKAction repeatActionForever:sequence]; [self runAction:repeat]; - (void)方法{ ... } – Roecrew

+3

不只是一種替代方法,但它的方式來做到這一點。例如,如果遊戲/場景/節點暫停,NSTimer不會停止發射。 – LearnCocos2D

+0

@ LearnCocos2D我假設OP已經設置了一切來管理/停止定時器。 – NobodyNada

4

在斯威夫特可用:

在雪碧包不使用NSTimer, GCD or performSelector:afterDelay:,因爲這些時序方法忽略了一個節點,現場的或視圖的暫停狀態。此外,您不知道遊戲循環中的哪一點會執行哪些操作,這可能會導致各種問題,具體取決於您的代碼實際執行的操作。

var actionwait = SKAction.waitForDuration(0.5) 
     var timesecond = Int() 
     var actionrun = SKAction.runBlock({ 
       timescore++ 
       timesecond++ 
       if timesecond == 60 {timesecond = 0} 
       scoreLabel.text = "Score Time: \(timescore/60):\(timesecond)" 
      }) 

     scoreLabel.runAction(SKAction.repeatActionForever(SKAction.sequence([actionwait,actionrun])))