Search code examples
iosswiftrandomarc4random

Understanding random numbers in iOS Swift 2


How do I make a random number continue to change over time in the program (I.E. become a new one within the range everytime I want to use it)?

I'm stumped. I've read more than 20 different posts and articles on how to generate random numbers in this language (which I'm pretty new to) and I just can't seem to get it to work.

I'm basically trying to get a random double from 1.0-3.0. I can do this pretty easily, but once it has selected that number it doesn't change. This is my code that I use:

var randomNumber:Double = (Double(arc4random() % 3) + 1);

Then I use this as a value for the line:

SKAction.waitForDuration(randomNumber)

Every time I run this I want to change the number again, but once the program starts it continues that same number (It's different every time i reset the program)

I understand how to generate the number, but I can't seem to find anything on updating it!

I've tried adding

randomNumber = (Double(arc4random() % 3) + 1);

into the code in a spot where it will be ran many times, but it still gives me the same thing.

I'm very familiar with c++ so if you're trying to explain something you can reference its style and I will most likely understand.


Solution

  • Use:

    SKAction.waitForDuration(sec: NSTimeInterval, withRange: NSTimeInterval) 
    

    where sec is the middle of the range in time you want to use, since range goes in a +- direction.

    So in your case you want:

    SKAction.waitForDuration(2, withRange: 2),  this will get you a range of 1 to 3 (-1 to 1 range)
    

    If for some reason you need a method that will constantly create a new random wait, you can always do:

    extension SKAction
    {
        func waitForRandomDuration() -> SKAction
        {
            var randomNumber:Double = (Double(arc4random() % 3) + 1);
            return SKAction.waitForDuration(randomNumber);
    
        }
    }
    

    And then make sure that you add this as a new action onto your sprite every time you need to get it done, if you store it into a variable, your randomness won't change.