Jos*_*ría 4 random nstimer performselector sprite-kit swift
以前,使用Objective-C我可以使用performSelector:以便在随机时间段之后重复一个动作,该动作可能在1-3秒之间变化.但由于我无法使用performSelector:在Swift中,我尝试过使用"NSTimer.scheduledTimerWithTimeInterval".它的工作原理是为了重复这个动作.但有一个问题.设置时间变量以调用将生成随机数的函数.但似乎NSTimer每次重复动作时都会使用相同的数字.
这意味着该动作不是随机执行的,而是在游戏开始时随机生成的一段时间之后执行,并且在整个游戏期间使用.
问题是:有没有办法设置NSTimer每次执行动作时创建一个随机数?或者我应该使用不同的方法?谢谢!
@ LearnCocos2D是正确的...使用SKActions或update场景中的方法.以下是使用update在随机时间段后重复操作的基本示例.
class YourScene:SKScene {
// Time of last update(currentTime:) call
var lastUpdateTime = NSTimeInterval(0)
// Seconds elapsed since last action
var timeSinceLastAction = NSTimeInterval(0)
// Seconds before performing next action. Choose a default value
var timeUntilNextAction = NSTimeInterval(4)
override func update(currentTime: NSTimeInterval) {
let delta = currentTime - lastUpdateTime
lastUpdateTime = currentTime
timeSinceLastAction += delta
if timeSinceLastAction >= timeUntilNextAction {
// perform your action
// reset
timeSinceLastAction = NSTimeInterval(0)
// Randomize seconds until next action
timeUntilNextAction = CDouble(arc4random_uniform(6))
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3708 次 |
| 最近记录: |