Random value in Swift

偶尔善良 提交于 2019-12-12 17:30:19

问题


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


回答1:


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)



回答2:


let sizeX = Int(CGRectGetMaxX(self.frame))
let tempRandX = Int(arc4random_uniform(sizeX))
var randomX = CGFloat(temptRandomX)

let sizeY = Int(CGRectGetMaxY(self.frame))
let tempRandY = Int(arc4random_uniform(sizeY))
var randomY = CGFloat(temptRandomY)

self.touchButton.position = CGPointMake(randomX, randomY)

Use this instead. Also tested it.




回答3:


this should do it

let sizeX = UInt32(CGRectGetMaxX(self.frame))
let randomX = CGFloat(arc4random_uniform(sizeX))

let sizeY = UInt32(CGRectGetMaxY(self.frame))
let randomY = CGFloat(arc4random_uniform(sizeY))

self.touchButton.position = CGPointMake(randomX, randomY)


来源:https://stackoverflow.com/questions/24466330/random-value-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!