Search code examples
swiftaxiscgrect

Random Spawning along X and Y axis


I am using CGRect to contain my spawning nodes within an location, which is below-

func CGRectMake(_ x: 90, _ y: 360, _ width: 260, _ height: 466) -> CGRect

My problem now is, I'm not sure how to spawn the nodes within the location with a random x and y axis? Should I use arc4random? Or is there another way of doing this?


Solution

  • arc4random would be ok.

    Use it like that :

    let rect = CGRectMake(x: 90, y: 360, width: 260, height: 466)
    let x = rect.origin.x + CGFloat(arc4random()) % rect.size.width
    let y = rect.origin.y + CGFloat(arc4random()) % rect.size.height
    let randomPoint = CGPointMake(x, y)
    

    Also, you should note that if you have reverse Y axis, you should use - instead of + in y line.