0

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

Astrum
  • 375
  • 6
  • 21
  • Possible duplicate of [How does one make random number between range for arc4random\_uniform()?](http://stackoverflow.com/questions/24132399/how-does-one-make-random-number-between-range-for-arc4random-uniform) – Tobi Nary Feb 01 '16 at 10:13
  • Probably a duplicate of [Pick a random element from an array](http://stackoverflow.com/questions/24003191/pick-a-random-element-from-an-array) – tebs1200 Feb 01 '16 at 11:04

1 Answers1

1

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])
tebs1200
  • 1,205
  • 12
  • 19
  • biggest rookie mistake by me I forgot all about indexes. xD But yes that did solve my problem thank you. – Astrum Feb 01 '16 at 11:11