如何在swift 2中设置随机颜色的计时器?
我想设置计时器并每5秒更改背景颜色。如何在swift 2中设置随机颜色的计时器?
我写了随机颜色代码和它的工作完美,但我试图把功能放在NSTimer中,我越来越迷恋。
2016年3月5日14:46:48.774啵冒险[6782:365555] ***终止应用程序 由于未捕获的异常 'NSInvalidArgumentException',原因: “ - [Boo_Adventure.GameScene更新]:无法识别选择发送到 例如0x7fe2cb741ac0'
游戏场景:
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random())/CGFloat(UInt32.max)
}
}
extension UIColor {
static func randomColor() -> UIColor {
let r = CGFloat.random()
let g = CGFloat.random()
let b = CGFloat.random()
// If you wanted a random alpha, just create another
// random number for that too.
return UIColor(red: r, green: g, blue: b, alpha: 2.5)
}
}
override func didMoveToView(view: SKView) {
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: false)
func update() {
self.view!.backgroundColor = UIColor.randomColor()
}
}
谢谢!
很少有什么问题在这里:
1)你想改变每5秒的颜色,但你设置repeats
参数false
,使您的自定义update()方法会只执行一次。将repeats
更改为true
。
2)您正试图更改视图(SKView)的背景颜色而不是场景的背景颜色。
这里是你如何与NSTimer
做到这一点:
override func didMoveToView(view: SKView) {
let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
func update(){
backgroundColor = UIColor.randomColor()
}
但NSTimer
不受场景的或视图的暂停状态,所以它可以带你到在某些情况下的麻烦。为了避免这种情况,您可以使用SKAction
。与SKAction做同样的事情是这样的:
override func didMoveToView(view: SKView) {
let wait = SKAction.waitForDuration(5)
let block = SKAction.runBlock({
[unowned self] in
self.backgroundColor = UIColor.randomColor()
})
let sequence = SKAction.sequence([wait,block])
runAction(SKAction.repeatActionForever(sequence), withKey: "colorizing")
}
这样一来,如果您暂停场景或视图,上色动作会(当场景/视图是取消暂停和取消暂停)将自动暂停。
你的功能update
看起来像它在计时器的关闭 - 但事实并非如此。取出来的功能,使它看起来像这样
override func didMoveToView(view: SKView) {
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: false)
}
func update() {
self.view!.backgroundColor = UIColor.randomColor()
}
它是否正在调用'update'函数? – Russell
当然!其权利 –
不知道是否能解决此问题,但根据NSTimer Class Reference选择应该有签名:
timerFireMethod:
尝试更新update
功能签名
func update(timer: NSTimer)
并更新此行:
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: false)
到:
Timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update:", userInfo: nil, repeats: false)
我需要把timerFireMethod放在什么地方? –
谢谢你!它的工作! –
我如何添加它过渡? –
如果我理解正确,可以使用[colorizeWithColor:colorBlendFactor:duration:](https://developer.apple.com/library/prerelease/mac/documentation/SpriteKit/Reference/SKAction_Ref/index.html#//apple_ref/occ/clm/SKAction/colorizeWithColor:colorBlendFactor:duration :)但这是另一个话题,你应该问一个新的问题... – Whirlwind