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)

    }

  }

}

最佳答案

您可以通过几种方式来做到这一点,下面是一个有关如何使用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()
        }

    }

  }


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

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


  尝试添加已经具有父级的SKNode


另外,您不会每秒更新一次标签的text属性。您可以一次执行整个for循环(只需不到一秒钟的时间即可完成)。

关于ios - Sprite Kit创建倒数计时器问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31637742/

10-11 17:13