在 Swift 中为 Sprite 创建随机位置

Creating a Random Position for a Sprite in Swift

我有一个圆形精灵,我想将它移动到 iOS 设备屏幕范围内的随机位置。我正在尝试在 Swift 中执行此操作,但我仍然是初学者,我什至不知道从哪里开始。有谁知道如何为精灵创建随机位置?提前致谢!

-文尼

假设您从场景中调用代码 class:

func spawnAtRandomPosition() {
    let height = self.view!.frame.height
    let width = self.view!.frame.width

    let randomPosition = CGPointMake(CGFloat(arc4random()) % height, CGFloat(arc4random()) % width)

    let sprite = SKSpriteNode()
    sprite.position = randomPosition
}

Swift3:

func spawnRandomPosition() {

let height = self.view!.frame.height
let width = self.view!.frame.width

let randomPosition = CGPoint(x:CGFloat(arc4random()).truncatingRemainder(dividingBy: height),
                                 y: CGFloat(arc4random()).truncatingRemainder(dividingBy: width))

let sprite = SKSpriteNode()
sprite.position = randomPosition
 }

Swift 3:

let randomPosition = CGPoint( x:CGFloat( arc4random_uniform( UInt32( floor( width  ) ) ) ),
                              y:CGFloat( arc4random_uniform( UInt32( floor( height ) ) ) )
                              )