2015-08-08 54 views
0

我有一個圓形精靈,我想移動到iOS設備屏幕範圍內的隨機位置。我試圖在Swift中做到這一點,但我仍然是初學者,我甚至不知道從哪裏開始。有誰知道如何爲精靈創建隨機位置?先謝謝你!在Swift中爲Sprite創建隨機位置

-Vinny

回答

1

讓我們假設你是從場景類調用代碼:

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 
} 
+0

謝謝非常! –

+0

不要忘記標記爲答案。 – s1ddok

5

斯威夫特3:

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 
} 
0

斯威夫特3:

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