Spawning a circle in a random spot on screen

前端 未结 3 573
闹比i
闹比i 2021-01-15 03:05

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 he

3条回答
  •  佛祖请我去吃肉
    2021-01-15 03:41

    Given the following random generators:

    public extension CGFloat {
        public static var random: CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) }
    
        public static func random(between x: CGFloat, and y: CGFloat) -> CGFloat {
            let (start, end) = x < y ? (x, y) : (y, x)
            return start + CGFloat.random * (end - start)
        }
    }
    
    public extension CGRect {
        public var randomPoint: CGPoint {
            var point = CGPoint()
            point.x = CGFloat.random(between: origin.x, and: origin.x + width)
            point.y = CGFloat.random(between: origin.y, and: origin.y + height)
            return point
        }
    }
    

    You can paste the following into a playground:

    import XCPlayground
    import SpriteKit
    
    let view = SKView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
    XCPShowView("game", view)
    
    let scene = SKScene(size: view.frame.size)
    view.presentScene(scene)
    
    let wait = SKAction.waitForDuration(0.5)
    let popIn = SKAction.scaleTo(1, duration: 0.25)
    let popOut = SKAction.scaleTo(0, duration: 0.25)
    let remove = SKAction.removeFromParent()
    
    let popInAndOut = SKAction.sequence([popIn, wait, popOut, remove])
    
    let addBall = SKAction.runBlock { [unowned scene] in
        let ballRadius: CGFloat = 25
        let ball = SKShapeNode(circleOfRadius: ballRadius)
        var popInArea = scene.frame
        popInArea.inset(dx: ballRadius, dy: ballRadius)
        ball.position = popInArea.randomPoint
        ball.xScale = 0
        ball.yScale = 0
        ball.runAction(popInAndOut)
        scene.addChild(ball)
    }
    
    scene.runAction(SKAction.repeatActionForever(SKAction.sequence([addBall, wait])))
    

    (Just make sure to also paste in the random generators, too, or to copy them to the playground's Sources, as well as to open the assistant editor so you can see the animation.)

提交回复
热议问题