How to create a timer in Spritekit?

2019-05-06 15:51发布

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'

2条回答
乱世女痞
2楼-- · 2019-05-06 16:20

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.

查看更多
Fickle 薄情
3楼-- · 2019-05-06 16:24

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])))
查看更多
登录 后发表回答