在我升级到 Swift 3 (Xcode 8) 之前,我的随机位置开始看起来像这样:
func randomStartPosition(range: Range<Int> = 45...(Int(self.frame.size.height)-45)) -> Int {
let min = range.startIndex
let max = range.endIndex
return Int(arc4random_uniform(UInt32(max - min))) + min }
转换后停止工作,因为它已更新为:
func randomSmallObjectsStartPosition(_ range: Range<Int> = 25...(Int(self.frame.size.height)-25)) -> Int {
let min = range.lowerBound
let max = range.upperBound
return Int(arc4random_uniform(UInt32(max - min))) + min }
这是因为我最终了解了 GamePlayKit:
开始:
import GameplayKit
然后,您可以使用 GamePlayKit 轻松创建新的随机变量:
您可以在苹果网站上阅读,但基本上这会在中间为您提供更多“点击”:
lazy var randomStartPosition = GKGaussianDistribution(randomSource: GKARC4RandomSource(), lowestValue: 0, highestValue:100)
这将循环遍历随机值,直到它们都被消耗完,然后重新开始。
lazy var randomShuffle = GKShuffledDistribution(randomSource: GKARC4RandomSource(), lowestValue: 0, highestValue:100)
最后是完全随机的值生成器:
lazy var totallyRandom = GKRandomDistribution(lowestValue: 1, highestValue: 100)
如何使用的示例:
MyObject.position = CGPoint(x: self.frame.size.width + 20, y: CGFloat(totallyRandom.nextInt()) )
这会将我的对象从最右侧的屏幕上移开,并将其放置在 Y 轴上完全随机的位置。