gpt4 book ai didi

ios - Sprite Kit 创建倒数计时器问题

转载 作者:行者123 更新时间:2023-11-29 01:48:51 26 4
gpt4 key购买 nike

timeLabel 应该从 60 倒计时到 0,但我还没有实现持续时间。例如 timeLabel.text = String(i)//每 1 秒执行一次 这样它就像一个真正的倒数计时器。我该怎么做。另一个问题是运行此代码时游戏不会在模拟器中启动。我得到一个错误,我被重定向到 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()
}

}

}

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

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

Attemped to add a SKNode which already has a parent

此外,您也没有每秒运行一次更新标签的文本属性。您将立即执行整个 for 循环(完成时间比一秒钟少得多)。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com