如何在Spritekit中创建一个计时器?

4
我已经知道如何在单视图应用程序中创建计时器,但不知道如何在Spritekit中创建。当我使用以下代码时,出现了两个错误(如下所示)。谁能帮我解决这个问题?谢谢,Jack。
计时器。
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'

不要使用NSTimer!请参见:https://dev59.com/bmAg5IYBdhLWcg3wG3wK#23978854 - CodeSmile
2个回答

4

在Swift中使用:

在Sprite Kit中不要使用NSTimer,GCD或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])))

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)method { ... }
- maelswarm
3
不仅是一种选择,而是唯一的方法。例如,如果暂停游戏/场景/节点,NSTimer不会停止触发。 - CodeSmile
@LearnCocos2D 我假设 OP 已经设置好了管理/停止计时器的一切。 - NobodyNada

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接