Swift: repeat an action after a random period of time

Previously, using Objective-C, I could use performSelector: to repeat the action after a random period of time, which can vary from 1-3 seconds. But since I cannot use performSelector: in Swift, I tried to use "NSTimer.scheduledTimerWithTimeInterval". And he works to repeat the action. But there's a problem. Set a temporary variable to call a function that will generate a random number. But it seems that NSTimer uses the same number every time it repeats the action.

This means that the action is not performed randomly, but instead, after a certain period of time, which is randomly generated at the beginning of the game and used throughout the game.

Question: is there a way to set NSTimer to create a random number every time it performs an action? Or should I use a different method? Thank!

+4
source share
3 answers

@ LearnCocos2D is right ... use SKActionsor updatemethod in your scene. Here is a basic use case updatefor repeating an action after a random period of time.

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))

        }

    }

}
+5
source

use let wait = SKAction.waitForDuration(sec, withRange: dur)in your code. SKAction.waitForDurationwith the parameter with the parameter Range will calculate a random time interval with an average time = sec and a possible range = dur

+3
source

Create a random time yourself and use it dispatch_afterto perform an action.

For more information, dispatch_aftersee here . Basically you can use this insteadperformSelector

0
source

Source: https://habr.com/ru/post/1547403/


All Articles