Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random value in Swift

I'm trying to have a value who is between 0 and the size of my screen. So i did it like this :

let sizeX = Int(CGRectGetMaxX(self.frame))
let sizeY = Int(CGRectGetMaxY(self.frame))
var randomX = CGFloat(arc4random()) % sizeX
var randomY = CGFloat(arc4random()) % sizeY
self.touchButton.position = CGPointMake(randomX, randomY)

I have this error : could not find an overload for '%' that accepts the supplied arguments

I need this to randomize the position of an SkSpriteNode, maybe is there a better solution ?

Thank you

like image 839
Quentin Avatar asked Jan 27 '26 05:01

Quentin


1 Answers

Convert the value that arc4random() returns to an Int and then convert the whole expression to a CGFloat:

var randomX = CGFloat(Int(arc4random()) % sizeX)
var randomY = CGFloat(Int(arc4random()) % sizeY)
self.touchButton.position = CGPointMake(randomX, randomY)
like image 168
Moon Cat Avatar answered Jan 29 '26 19:01

Moon Cat