iPhone気泡

気泡っぽいものをふわふわ表示するiPhoneアプリのサンプルコードを描いてみます。

import UIKit

import SpriteKit

class ViewController: UIViewController, SKSceneDelegate {

    weak var scene : SKScene?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.setupScene()

    }

    

    func setupScene() {

        let sv = SKView(frame: self.view.bounds)

        let scene = SKScene(size: sv.frame.size)

        scene.delegate = self

        scene.backgroundColor = UIColor(hue: 0.6, saturation: 0.2, brightness: 1, alpha: 1)

        sv.presentScene(scene)

        self.view.addSubview(sv)

        self.scene = scene

    }

    

    func update(currentTime: NSTimeInterval, forScene scene: SKScene) {

        if arc4random_uniform(50) < 4 {

            self.createBubble()

        }

        

        [self.scene!.enumerateChildNodesWithName(“bubble”, usingBlock: {

            if $0.0.position.y > 800 {

                $0.0.removeFromParent()

            }

        })]

    }

    func createBubble() {

        let w = UInt32(CGRectGetMaxX(self.view.bounds) / 2.0)

        let r = CGFloat(arc4random_uniform(w)) * 0.2

        let x = CGFloat(arc4random_uniform(w)) * 2.0

        let y = CGFloat(arc4random_uniform(50))

        let bubble = SKShapeNode(circleOfRadius: r)

        bubble.name = “bubble”

        bubble.position = CGPoint(x: x, y: y)

        bubble.lineWidth = 2.0

        

        let hue = CGFloat(arc4random_uniform(30)) * 0.1

        if hue < 1.0 { bubble.strokeColor = UIColor(hue: hue, saturation: 0.2, brightness: 1, alpha: 1) }

        self.scene?.addChild(bubble)

        

        let velocityY = pow(r, 1.3) + 100

        let velocityXR = CGFloat(arc4random_uniform(20))

        let velocityXL = CGFloat(arc4random_uniform(20))

        bubble.runAction(SKAction.repeatActionForever(

            SKAction.group([

                SKAction.moveBy(CGVector(dx:0, dy:velocityY), duration: 2.0),

                SKAction.sequence([

                    SKAction.moveBy(CGVector(dx: velocityXR, dy:0), duration: 1.0),

                    SKAction.moveBy(CGVector(dx: velocityXL, dy:0), duration: 1.0)

                    ])

            ])))

    }

}