【问题标题】:Label not changing countdown timer SpriteKit Objective C?标签不改变倒数计时器SpriteKit Objective C?
【发布时间】:2014-11-29 13:52:03
【问题描述】:

Edit no.2 ,好的,我想我现在已经把它归结为重点了。我已经使用了您的所有建议,并使用断点进行了测试,所以谢谢。

我需要做的最后一点是运行这个等待操作。

if (timerStarted == YES) {

    [countDown runAction:[SKAction waitForDuration:1]];
    if (countDownInt > 0) {
    countDown.text = [NSString stringWithFormat:@"%i", countDownInt];
    countDownInt = countDownInt - 1.0;
    [self Timer];

    }else{
        countDown.text = [NSString stringWithFormat:@"Time Up!"];
    }

runAction: 部分似乎不起作用。我猜这是因为我选择了错误的节点来代替(SKLabelNode“countDown”)。我可以使用哪个节点来运行此代码?

感谢迄今为止帮助过的所有人

【问题讨论】:

  • 怎么了?只要 timeLeft > 0,您就可以创建一个全新的标签节点每一帧,而不会删除旧的标签节点。一秒钟后,您最终会得到大约 60 个标签。您应该有一个标签,并且只更新该标签的文本属性。

标签: objective-c sprite-kit sklabelnode


【解决方案1】:

这是一个如何在 SpriteKit 中实现倒数计时器的示例。

首先,声明一个方法,该方法创建 1) 一个标签节点以显示剩余时间和 2) 更新标签的适当操作,等待一秒钟,然后冲洗/起泡/重复

- (void) createTimerWithDuration:(NSInteger)seconds position:(CGPoint)position andSize:(CGFloat)size {
    // Allocate/initialize the label node
    countDown = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    countDown.position = position;
    countDown.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
    countDown.fontSize = size;
    [self addChild: countDown];
    // Initialize the countdown variable
    countDownInt = seconds;
    // Define the actions
    SKAction *updateLabel = [SKAction runBlock:^{
        countDown.text = [NSString stringWithFormat:@"Time Left: %ld", countDownInt];
        --countDownInt;
    }];
    SKAction *wait = [SKAction waitForDuration:1.0];
    // Create a combined action
    SKAction *updateLabelAndWait = [SKAction sequence:@[updateLabel, wait]];
    // Run action "seconds" number of times and then set the label to indicate
    // the countdown has ended
    [self runAction:[SKAction repeatAction:updateLabelAndWait count:seconds] completion:^{
        countDown.text = @"Time's Up";
    }];
}

然后使用持续时间(以秒为单位)和标签的位置/大小调用方法。

CGPoint location = CGPointMake (CGRectGetMidX(self.view.frame),CGRectGetMidY(self.view.frame));
[self createTimerWithDuration:20 position:location andSize:24.0];

【讨论】:

    【解决方案2】:

    我不会使用更新方法。使用 SKActions 制作计时器。举个例子

    id wait = [SKAction waitForDuration:1];
    id run = [SKAction runBlock:^{
        // After a second this is called
    }];
    [node runAction:[SKAction sequence:@[wait, run]]];
    

    即使这只会运行一次,如果您希望每秒或任何时间间隔被调用,您始终可以将其嵌入到 SKActionRepeatForever 中。 来源: SpriteKit - Creating a timer

    【讨论】:

    • 我不确定如何使用上面的代码实现这一点
    • 所以无论你想在哪里开始你的计时器。创建一个等待的操作(以您想要的任何时间间隔)。那么第二个动作就是你在等待 x 时间后想要做的事情。您可以将倒计时标签代码的设置放在该运行块内,并在保存当前时间的某处减少一个 int。然后再做一个永远重复这些动作的动作。检查与标签相同的代码块,如果 currentTime
    • 不好意思打扰了,我应该把什么对象作为节点?
    • 你当前所处的场景。
    猜你喜欢
    • 2012-05-26
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2015-09-30
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多