0

So I have to randomize an x position. But for some reason the middle is 0 and therefore I need to do negative max x and positive max x. It's a little hard to explain so here is the code:

let height = UInt32(self.view!.frame.height)
    let nHeight = ((height - height) - height)

    let randomXPosition = Int(arc4random_uniform(UInt32(nHeight)) + height)

This doesn't give me any errors but when I run it crashes. I need a way to randomize the value for negative max X and positive max X so that the object is randomized in the screen.

  • Perhaps u can use an offsetter ? if the resolution u are dealing with is -400 to 400, perhaps you can work with number from 0 to 800, then adjust your final positions accordingly? Also, not sure it's a good idea to mix INT with an UNSIGNED INT since you can run into overflow issues. – Bill Roberts Mar 14 '17 at 20:12
  • http://stackoverflow.com/a/34712601/2303865 you can use negative values with this extension – Leo Dabus Mar 14 '17 at 20:30

1 Answers1

3

If you need to generate a random number between -x and x then just create a random number between 0 and 2x and subtract x. arc4random_uniform(x * 2) - x.

creeperspeak
  • 5,403
  • 1
  • 17
  • 38