Search code examples
arraysswiftrandomcgfloat

Getting a random CGFloat value from an array?


I have an array that holds CGFloat values and I am trying to figure out how I would go about randomising through this array to get a random x co-ordinate:

let xAxisSpawnLocations: [CGFloat] = [screenWidth + 150, screenWidth + 100, screenWidth + 50 , screenWidth - 50, screenWidth - 100, screenWidth - 150]  

because I have to put them into a line of code that will position an object on the map.

obstacle.position = CGPoint(x: ARRAY VALUE HERE, y: yAxisSpawnLocations[0])

I have tried looking up how to randomise through an array but it only has it for Int32 values.

Can some please provide and example on how to do this.

Here is the full code for reference if you need to look at it:

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)
        }
      }
    }

The xLocation needs to be replaced by the randomiser


Solution

  • While you're array may be storing CGFloat values, the array indexes will still be integers. Arrays always have integer based indexes regardless of what they are storing.

    You simply want to generate a random integer between 0 and the length of the array and access the element at that index:

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