iPhoneたこやき

たこ焼きをひっくり返すiPhoneアプリのサンプルコードを描いてみます。

import UIKit

import SceneKit

class ViewController: UIViewController {

    weak var sceneView : SCNView?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        setupScene()

        createIronPlate()

        createTakoyaki()

        createCamera()

    }

    func setupScene() {

        let sv = SCNView(frame: view.bounds)

        sv.backgroundColor = UIColor(hue: 0, saturation: 0.3, brightness: 0.9, alpha: 1)

        sv.scene = SCNScene()

        sv.autoenablesDefaultLighting = true

        self.view.addSubview(sv)

        

        self.sceneView = sv

    }

    func createIronPlate() {

        let plate = SCNBox(width: 40, height: 1, length: 16, chamferRadius: 0.2)

        plate.firstMaterial?.diffuse.contents = UIColor.blackColor()

        let plateNode = SCNNode(geometry: plate)

        self.sceneView?.scene?.rootNode.addChildNode(plateNode)

    }

    

    func createTakoyaki() {

        [Int](09).each { i in

            

            let ball = SCNSphere(radius: 2)

            ball.firstMaterial?.diffuse.contents = {

                let l = CALayer()

                l.frame = CGRect(x: 0, y: 0, width: 200, height: 200)

                l.backgroundColor = UIColor(hue: 0.1, saturation: 0.2, brightness: 1, alpha: 1).CGColor

                let sub = CALayer()

                sub.frame = CGRect(x: 0, y: 0, width: 200, height: 100)

                sub.backgroundColor = UIColor(hue: 0.1, saturation: 0.8, brightness: 0.7, alpha: 1).CGColor

                l.addSublayer(sub)

                return l

            }()

            

            let takoyaki = SCNNode(geometry: ball)

            takoyaki.name = “takoyaki”

            let x =  168 * Float(i % 5)

            let z = 7 * Float(i/5) – 3.5

            takoyaki.position = SCNVector3(x: x, y: 0, z: z)

            self.sceneView?.scene?.rootNode.addChildNode(takoyaki)

        }

    }

    

    func createCamera() {

        let camera = SCNNode()

        camera.camera = SCNCamera()

        camera.position = SCNVector3(x: –17, y: 30, z: 60)

        camera.rotation = SCNVector4(x: 1, y: 0.5, z: 0, w: –0.5)

        self.sceneView?.scene?.rootNode.addChildNode(camera)

    }

    

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        let p = touches.anyObject()!.locationInView(self.sceneView)

        if let hit = self.sceneView?.hitTest(p, options: [SCNHitTestSortResultsKey : true])?.first as? SCNHitTestResult {

            if hit.node.name == “takoyaki” {

                hit.node.runAction(SCNAction.rotateByAngle(CGFloat(M_PI), aroundAxis: SCNVector3(x: 1, y: 0, z: 0), duration: 0.4))

            }

        }

    }

}

extension Array {

    func each(doit:(T) -> Void) { for i in self {doit(i)} }

}