John John
John John

Reputation: 3

Creating a Random Position for a Sprite in Swift

I have a circle sprite that I would like to move to a random position within the confines of the iOS device's screen. I am trying to do this in Swift, but I am still I beginner and I don't even know where to start. Does anyone know what to do to create a random position for the sprite? Thank you in advance!

-Vinny

Upvotes: 0

Views: 4042

Answers (3)

richtea
richtea

Reputation: 51

Swift 3:

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

Upvotes: 0

user6818154
user6818154

Reputation:

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

Upvotes: 5

s1ddok
s1ddok

Reputation: 4654

Let's assume you are calling your code from the scene 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
}

Upvotes: 1

Related Questions