Search code examples
xcodeswiftmarginarc4random

beginner swift sprite kit - arc4random and getting screen size


I want to get a random number to be in between my background width and to be 37 pixels away from the margins but it doesn't work

var width = UInt32(self.frame.width - 74)
var newX = Int(arc4random)%width)
var newY = Int(self.frame.height+10)
var pos = CGPoint(x: newX + 37, y: newY)

Solution

  • arc4random is a function, you need to call it. And you should be using arc4random_uniform anyway.

    var newX = Int(arc4random_uniform(width))
    

    Also, because Swift is still terrible about implicit conversions, you need to convert the arguments to the CGPoint:

    var pos = CGPoint(x: CGFloat(newX + 37), y: CGFloat(newY))
    

    And if you don't intend to change these later in the method, you should use let instead of var.