John John John John - 1 year ago 125
Swift Question

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!


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download