从数组中获取随机 CGFloat 值?
Getting a random CGFloat value from an array?
我有一个包含 CGFloat 值的数组,我正在尝试弄清楚如何通过该数组随机化以获得随机 x 坐标:
let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]
因为我必须将它们放入一行代码中,以便在地图上定位一个对象。
obstacle.position = CGPoint(x: ARRAY VALUE HERE, y: yAxisSpawnLocations[0])
我曾尝试查找如何通过数组进行随机化,但它仅适用于 Int32 值。
能否提供有关如何执行此操作的示例。
这里是完整的代码,需要看的可以参考:
let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]
let yAxisSpawnLocations: [CGFloat] = [0]
for xLocation in xAxisSpawnLocations {
for (var i = 0; i < Int(numberOfObjectsInLevel); i++) {
let obstacle:Object = Object()
obstacle.theType = LevelType.road
obstacle.createObject()
addChild(obstacle)
obstacle.position = CGPoint(x: xLocation, y: yAxisSpawnLocations[0])
obstacle.zPosition = 9000
// addChild(greenFrog)
}
}
}
xLocation 需要被随机化器替换
虽然您的数组可能正在存储 CGFloat
值,但数组索引仍然是整数。数组总是有基于整数的索引,不管它们存储什么。
您只想生成一个介于 0 和数组长度之间的随机整数并访问该索引处的元素:
let randx = xAxisSpawnLocations[Int(arc4random_uniform(UInt32(xAxisSpawnLocations.count)))]
obstacle.position = CGPoint(x: randx, y: yAxisSpawnLocations[0])
我有一个包含 CGFloat 值的数组,我正在尝试弄清楚如何通过该数组随机化以获得随机 x 坐标:
let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]
因为我必须将它们放入一行代码中,以便在地图上定位一个对象。
obstacle.position = CGPoint(x: ARRAY VALUE HERE, y: yAxisSpawnLocations[0])
我曾尝试查找如何通过数组进行随机化,但它仅适用于 Int32 值。
能否提供有关如何执行此操作的示例。
这里是完整的代码,需要看的可以参考:
let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]
let yAxisSpawnLocations: [CGFloat] = [0]
for xLocation in xAxisSpawnLocations {
for (var i = 0; i < Int(numberOfObjectsInLevel); i++) {
let obstacle:Object = Object()
obstacle.theType = LevelType.road
obstacle.createObject()
addChild(obstacle)
obstacle.position = CGPoint(x: xLocation, y: yAxisSpawnLocations[0])
obstacle.zPosition = 9000
// addChild(greenFrog)
}
}
}
xLocation 需要被随机化器替换
虽然您的数组可能正在存储 CGFloat
值,但数组索引仍然是整数。数组总是有基于整数的索引,不管它们存储什么。
您只想生成一个介于 0 和数组长度之间的随机整数并访问该索引处的元素:
let randx = xAxisSpawnLocations[Int(arc4random_uniform(UInt32(xAxisSpawnLocations.count)))]
obstacle.position = CGPoint(x: randx, y: yAxisSpawnLocations[0])