了解iOS Swift 2中的随机数 [英] Understanding random numbers in iOS Swift 2
问题描述
我如何使程序中的随机数不断变化(IE会在我每次使用它的范围内变成新的随机数)?
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)?
我很沮丧我已经阅读了20多篇有关如何使用这种语言生成随机数的文章和文章(我很陌生),但我似乎无法使其正常工作。
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.
我基本上是在尝试从1.0-3.0随机获得一个两倍。我可以很容易地做到这一点,但是一旦选择了这个数字,它就不会改变。这是我使用的代码:
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!
我尝试添加
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.
我对c ++非常熟悉,因此,如果您试图解释某些内容,可以参考其样式,我很可能会理解。
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.
推荐答案
使用:
SKAction.waitForDuration(sec: NSTimeInterval, withRange: NSTimeInterval)
其中sec是您想要的时间范围的中间
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.
这篇关于了解iOS Swift 2中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!