【问题标题】:Swift: Repeat action after a random period of timeSwift:随机一段时间后重复动作
【发布时间】:2014-07-07 12:20:57
【问题描述】:

以前,在 Objective-C 中,我可以使用 performSelector: 在随机时间段(可能在 1-3 秒之间变化)后重复一个动作。但由于我无法使用 performSelector: 在 Swift 中,我尝试使用“NSTimer.scheduledTimerWithTimeInterval”。它可以重复操作。但有一个问题。设置时间变量以调用将生成随机数的函数。但似乎 NSTimer 每次重复操作时都使用相同的数字。

这意味着该动作不是随机执行的,而是在游戏开始时随机生成的一段时间后执行,并在整个游戏过程中使用。

问题是:有没有办法设置 NSTimer 在每次执行操作时创建一个随机数?还是我应该使用不同的方法?谢谢!

【问题讨论】:

  • 如果你在定时器运行后调用的选择器中重新创建定时器会怎样?
  • 在 sprite kit 或 cocos2d 中使用 skactions 或 update:,从不使用 nstimer、gcd dispatch 或 performselector,详情见这里:stackoverflow.com/a/23978854/201863
  • @LearnCocos2D 你能帮我把这段代码翻译成 Swift 吗?谢谢!
  • 到目前为止我还没有接触过swift......

标签: random swift sprite-kit nstimer performselector


【解决方案1】:

@LearnCocos2D 是对的...在您的场景中使用SKActionsupdate 方法。下面是一个使用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))

        }

    }

}

【讨论】:

  • 调用 self.update 方法时应该传递什么参数?感谢您的回答!
  • 另外,我该如何延迟操作?我的意思是,如果我使用它,则在加载场景时开始执行动作。如何延迟更新发生,比如场景加载后 10 秒?谢谢!
  • 你永远不会直接调用更新方法。此图片将向您展示评估场景动作的顺序:developer.apple.com/library/ios/documentation/GraphicsAnimation/…
  • 这里的概述部分也会有所帮助:developer.apple.com/library/ios/documentation/SpriteKit/…
  • 还有一个问题。如果我想安排在游戏后期发生的动作怎么办?例如,如果我在游戏开始时丢了一颗炸弹,我想要在用户玩了 20 秒或获得超过 15 分时再丢两颗炸弹。我可以使用 performSelector afterDelay:x 来做到这一点。我怎么能在这里做到这一点?
【解决方案2】:

在您的代码中使用let wait = SKAction.waitForDuration(sec, withRange: dur)SKAction.waitForDuration 带有 withRange 参数将计算随机时间间隔,平均时间 = 秒,可能范围 = dur

【讨论】:

    【解决方案3】:

    自己生成一个随机时间并使用dispatch_after 执行操作。

    有关dispatch_after 的更多信息,请参阅here。基本上你可以用这个代替performSelector

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-15
      • 2014-12-01
      • 2017-05-14
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多