iPhone箱ロール

箱を分割、回転させて色を変えるiPhoneアプリのサンプルコードを描いてみます。

import UIKit

import SceneKit

class ViewController: UIViewController {

    weak var sceneView : SCNView?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        setupScene()

        createBox()

        createCamera()

    }

    

    func setupScene() {

        let sv = SCNView(frame: view.bounds)

        sv.backgroundColor = UIColor.lightGrayColor()

        sv.scene = SCNScene()

        sv.autoenablesDefaultLighting = true

        view.addSubview(sv)

        

        sceneView = sv

    }

    

    func createBox() {

        let box = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0)

        var materials = [SCNMaterial]()

        [UIColor.yellowColor(), UIColor.greenColor(), UIColor.purpleColor(),

        UIColor.orangeColor(), UIColor.blueColor(), UIColor.brownColor()].each { color in

            let material = SCNMaterial()

            material.diffuse.contents = color

            materials.append(material)

        }

        box.materials = materials

        [Int](025).map { (i:Int) -> (x:Int, y:Int) in

            return (i % 5, i / 5)

        }

        .each {(x, y) in

            let node = SCNNode(geometry: box)

            node.name = \(x + 5 * y)”

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

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

        }

    }

    

    func createCamera() {

        let camera = SCNNode()

        camera.camera = SCNCamera()

        camera.position = SCNVector3(x: 2, y: 2, z: 10)

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

    }

    var count = 0

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        let n = sceneView?.scene?.rootNode.childNodeWithName(\(count)”, recursively: false)

        n?.runAction(SCNAction.rotateByX(0, y: CGFloat(M_PI), z: 0, duration: 1.0))

        count = (count + 1) % 25

    }

    

}

extension Array {

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

}