从数组中获取随机CGFloat值?

时间:2016-02-01 10:10:46

标签: arrays swift random cgfloat

我有一个包含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需要由随机用户替换

1 个答案:

答案 0 :(得分:1)

虽然您的数组可能存储CGFloat值,但数组索引仍然是整数。数组总是有基于整数的索引,无论它们存储什么。

您只想生成介于0和数组长度之间的随机整数,并访问该索引处的元素:

let randx = xAxisSpawnLocations[Int(arc4random_uniform(UInt32(xAxisSpawnLocations.count)))]
obstacle.position = CGPoint(x: randx, y: yAxisSpawnLocations[0])