Search code examples
randomswiftsprite-kitnstimerperformselector

Swift: Repeat action after a random period of time


Previously, with Objective-C I could use performSelector: in order to repeat an action after a random period of time which could vary between 1-3 seconds. But since I'm not able to use performSelector: in Swift, I've tried using "NSTimer.scheduledTimerWithTimeInterval". And it works in order to repeat the action. But there is a problem. On set the time 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.

What that means is that the action is not performed randomly, but instead, after a set period of time that is generated randomly at the beginning of the game and it is used during all the game.

The question is: Is there any way to set the NSTimer to create a random number every time it executes the action? Or should I use a different method? Thanks!


Solution

  • @LearnCocos2D is right... use SKActions or the update method in your scene. Here is a basic example of using update to repeat 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))
    
            }
    
        }
    
    }