因此,当我尝试根据分数将时间间隔变量频率更改为较低的数字时,我设置了这个定时器,用于在称为“频率”的时间间隔变量上运行特定功能(如下所示)数字它似乎没有改变它发射的速率它似乎同时发射,即使频率变为较低的数字
override func didMove(to view: SKView) {
Timer.scheduledTimer(timeInterval: frequency, target: self, selector: #selector(GameScene.spawnFallingOjects), userInfo: nil, repeats: true)
}
func spawnFallingOjects() {
if (GameState.current == .playing || GameState.current == .blackstone) {
guard usingThirdEye == false else { return }
let scoreLabel = childNode(withName: "scoreLabel") as! Score
let lane = [-100, -50 , 0, 50, 100]
let duration = 3.0
switch scoreLabel.number {
case 0...50:
frequency = 6.0
print("frequency has changed: \(frequency)")
case 51...100:
frequency = 4.5
print("frequency has changed: \(frequency)")
case 101...200000:
frequency = 1.1
print("frequency has changed: \(frequency)")
default:
return
}
let randomX = lane[Int(arc4random_uniform(UInt32(lane.count)))]
let object:Object = Object()
object.createFallingObject()
object.position = CGPoint(x: CGFloat(randomX), y: self.size.height)
object.zPosition = 20000
addChild(object)
let action = SKAction.moveTo(y: -450, duration: duration)
object.run(SKAction.repeatForever(action))
}
}
当频率数字变为较低的数字时,如何让计时器更快点火?我应该在功能结束时重新创建计时器吗?
答案 0 :(得分:2)
你实际上应该避免使用Timer,Sprite套件有自己的时间功能,而且Timer不能正常使用它,并且真的很难管理。
相反,请使用SKAction等待并解雇:
let spawnNode = SKNode()
override func didMove(to view: SKView) {
let wait = SKAction.wait(forDuration:frequency)
let spawn = SKAction.run(spawnFallingObjects)
spawnNode.run(SKAction.repeatForever(SKAction.sequence([wait,spawn])))
addChild(spawnNode)
}
然后为了加快速度,请执行:
switch scoreLabel.number {
case 0...50:
spawnNode.speed = 1
print("speed has changed: \(spawnNode.speed)")
case 51...100:
spawnNode.speed = 1.5
print("speed has changed: \(spawnNode.speed)")
case 101...200000:
spawnNode.speed = 2
print("speed has changed: \(spawnNode.speed)")
default:
return
}
答案 1 :(得分:0)
timeInterval
的{{1}}属性是readonly属性。 (而且您的代码并不是要尝试将新的Timer
写入属性...)
我应该在函数末尾重新创建计时器吗?
差不多是的。只是你没有必要在最后。
更改方法标题如下:
frequency
您可以通过参数func spawnFallingOjects(_ timer: Timer) {
访问已解雇的Timer
,因此您可能需要在timer
之后编写类似的内容:
switch scoreLabel.number {...}
您可以修改现有 if frequency != timer.timeInterval {
//Invalidate old Timer...
timer.invalidate()
//And then allocate new one
Timer.scheduledTimer(timeInterval: frequency, target: self, selector: #selector(GameScene.spawnFallingOjects), userInfo: nil, repeats: true)
}
的{{1}}属性(如果仍然是fireDate
),但重新创建Timer
实例并不是一个繁重的操作(与创建isValid
实例),因此重新创建新的Timer
似乎更容易一些。