Sprite Kit创建倒计时器问题

时间:2015-07-26 13:52:19

标签: ios swift for-loop sprite-kit

timeLabel应该从60倒数到0,但我还没有实现持续时间。例如timeLabel.text = String(i) //implement every 1 second因此它将类似于真正的倒计时器。我该怎么做另一个问题是,在运行此代码时,游戏不会在模拟器中启动。我收到错误,我被重定向到AppDelegate.swift文件:class AppDelegate: UIResponder, UIApplicationDelegate { //error: Thread 1: signal SIGABRT

class GameScene: SKScene {

var timeLabel = SKLabelNode()

override func didMoveToView(view: SKView) {   

    for var i = 60; i > 0; i-- {

        timeLabel.text = String(i)
        timeLabel.position = CGPointMake(frame.midX, frame.midY)
        timeLabel.fontColor = UIColor.blackColor()
        timeLabel.fontSize = 70
        timeLabel.fontName = "Helvetica"
        self.addChild(timeLabel)

    }

  }

}

1 个答案:

答案 0 :(得分:1)

您可以通过以下几种方式执行此操作,以下是有关如何使用SKAction更新标签文本(计数器)的示例:

  import SpriteKit

  class GameScene: SKScene {

    let timeLabel = SKLabelNode(fontNamed: "Geneva")
    var counter = 60

    override func didMoveToView(view: SKView) {

        timeLabel.text = "60"
        timeLabel.position = CGPointMake(frame.midX, frame.midY)
        timeLabel.fontColor = UIColor.blackColor()
        timeLabel.fontSize = 40

        self.addChild(timeLabel)
    }


    func countdown(){

        let updateCounter = SKAction.runBlock({

            self.timeLabel.text = "\(self.counter--)"

            if(self.counter == 0){
                self.counter = 60
            }

        })



        timeLabel.text = "60"
        timeLabel.position = CGPointMake(frame.midX, frame.midY)
        timeLabel.fontColor = UIColor.blackColor()
        timeLabel.fontSize = 40


        let countdown = SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration(1),updateCounter]))


        //You can run an action with key. Later, if you want to stop the timer, are affect in any way on this action, you can access it by this key
        timeLabel.runAction(countdown, withKey:"countdown")

    }

    func stop(){

        if(timeLabel.actionForKey("countdown") != nil){


            timeLabel.removeActionForKey("countdown")

        }

    }


    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {


        if(timeLabel.actionForKey("countdown") == nil){
            self.countdown()
        }

    }

  }

我在这里做的是每秒更新标签的文本属性。为此,我创建了一个更新计数器变量的代码块。使用动作序列每秒调用该代码块。

请注意,您当前的代码尝试在每个循环中添加标签。节点只能有一个父节点,并且应用程序会崩溃并显示以下错误消息:

  

尝试添加已有父级的SKNode

此外,您还没有在一秒钟内运行更新标签的文本属性。您正在一次执行整个for循环(这比在一秒钟内完成的时间少得多)。

相关问题