【问题标题】:How to create a timer in Spritekit?如何在 Spritekit 中创建计时器?
【发布时间】:2014-06-16 03:45:26
【问题描述】:

我已经知道如何在单视图应用程序中制作计时器,但不是 Spritekit。当我使用以下代码时,出现 2 个错误(如下所列)。谁能帮我解决这个问题?谢谢,杰克。

计时器。

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'

【问题讨论】:

标签: ios objective-c sprite-kit nstimer


【解决方案1】:

在 Swift 中可用:

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

【讨论】:

    【解决方案2】:

    您将创建的NSTimer 分配给SKLabelNode。要修复您的第一个错误,请将最后一行更改为:

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

    您收到第二个错误,因为您正在设置计时器以调用名为 Timercount 的方法,但您没有。

    【讨论】:

    • NSTimer 的替代方法是使用 SKActions。 SKAction *wait = [SKAction waitForDuration:1.0f]; SKAction *sequence = [SKAction 序列:@[[SKAction performSelector:@selector(method:) onTarget:self], 等待]]; SKAction *repeat = [SKAction repeatActionForever:sequence]; [自运行动作:重复]; - (void)method { ... }
    • 不只是一种选择,而是实现它的方法。例如,如果游戏/场景/节点暂停,NSTimer 不会停止触发。
    • @LearnCocos2D 我假设 OP 已经设置好所有东西来管理/停止计时器。
    猜你喜欢
    • 2019-01-29
    • 2016-06-19
    • 1970-01-01
    • 2023-04-09
    • 2017-10-30
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多