4

Ive figured out how to make a timer in a single-view application, but not Spritekit. When I use the following code, I get 2 errors(listed below). Can anyone help me out with this? Thanks, Jack.

The timer.

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];

The errors

Incompatible pointer types assigned to 'SKLabelNode*' from 'NSTimer*'
Undeclared selector 'Timercount'
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user3587361
  • 41
  • 1
  • 2

2 Answers2

4

In Swift usable:

In Sprite Kit do not use NSTimer, GCD or performSelector:afterDelay: because these timing methods ignore a node's, scene's or the view's paused state. Moreover you do not know at which point in the game loop they are executed which can cause a variety of issues depending on what your code actually does.

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])))
0

You are assigning the NSTimer you created to an SKLabelNode. To fix your first error, change the last line to:

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

You are getting the second error because you are setting the timer to call a method called Timercount, but you don't have one.

NobodyNada
  • 7,529
  • 6
  • 44
  • 51
  • 3
    Also an alternative to the NSTimer is to use 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)method { ... } – maelswarm Apr 30 '14 at 02:41
  • 3
    not just an alternative but THE way to do it. NSTimer won't stop firing if the game/scene/node is paused for instance. – CodeSmile Apr 30 '14 at 08:03
  • @LearnCocos2D I am assuming that the OP has everything set up already to manage/stop the timer. – NobodyNada Apr 30 '14 at 14:23