Reputation: 3
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
Reputation: 51
Swift 3:
let randomPosition = CGPoint( x:CGFloat( arc4random_uniform( UInt32( floor( width ) ) ) ),
y:CGFloat( arc4random_uniform( UInt32( floor( height ) ) ) )
)
Upvotes: 0
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
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