Search code examples
iosswiftrandomarc4random

Spawning a circle in a random spot on screen


I've been racking my brain and searching here and all over to try to find out how to generate a random position on screen to spawn a circle. I'm hoping someone here can help me because I'm completely stumped. Basically, I'm trying to create a shape that always spawns in a random spot on screen when the user touches.

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenHeight = screenSize.height
        let screenWidth = screenSize.width

        let currentBall = SKShapeNode(circleOfRadius: 100)
        currentBall.position = CGPointMake(CGFloat(arc4random_uniform(UInt32(Float(screenWidth)))), CGFloat(arc4random_uniform(UInt32(Float(screenHeight)))))

        self.removeAllChildren()
        self.addChild(currentBall)
}

If you all need more of my code, there really isn't any more. But thank you for whatever help you can give! (Just to reiterate, this code kind of works... But a majority of the spawned balls seem to spawn offscreen)


Solution

  • The problem there is that you scene is bigger than your screen bounds

    let viewMidX = view!.bounds.midX
    let viewMidY = view!.bounds.midY
    print(viewMidX)
    print(viewMidY)
    
    let sceneHeight = view!.scene!.frame.height
    let sceneWidth = view!.scene!.frame.width
    print(sceneWidth)
    print(sceneHeight)
    
    let currentBall = SKShapeNode(circleOfRadius: 100)
    currentBall.fillColor = .green
    
    let x = view!.scene!.frame.midX - viewMidX + CGFloat(arc4random_uniform(UInt32(viewMidX*2)))
    let y = view!.scene!.frame.midY - viewMidY + CGFloat(arc4random_uniform(UInt32(viewMidY*2)))
    print(x)
    print(y)
    
    currentBall.position = CGPoint(x: x, y: y)
    view?.scene?.addChild(currentBall)
    
    self.removeAllChildren()
    self.addChild(currentBall)