iPhoneポールフォール

ポールのにそって箱が落ちていくiPhoneアプリのサンプルコードを描いてみます。

import UIKit

import SceneKit

class ViewController: UIViewController, SCNSceneRendererDelegate {

    weak var scene : SCNScene?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor(hue: 0.4, saturation: 0.5, brightness: 0.8, alpha: 1)

        self.setupScene()

        self.createPole()

        self.createCamera()

    }

    func setupScene() {

        let w = CGRectGetMaxX(self.view.bounds)

        let sv = SCNView(frame: CGRect(x: 0, y: 0, width: w, height: w));

        sv.scene = SCNScene()

        sv.backgroundColor = UIColor(hue: 0, saturation: 0.05, brightness: 1.0, alpha: 1)

        sv.delegate = self

        self.view.addSubview(sv)

        

        self.scene = sv.scene

    }

    

    func createPole() {

        let pole = SCNCylinder(radius: 1, height: 100)

        pole.firstMaterial?.diffuse.contents = UIColor(hue: 0.4, saturation: 0.5, brightness: 0.8, alpha: 1)

        let poleNode = SCNNode(geometry: pole)

        poleNode.name = “pole”

        self.scene?.rootNode.addChildNode(poleNode)

        

        poleNode.physicsBody = SCNPhysicsBody.staticBody()

    }

    

    func createCamera() {

        let camera = SCNNode()

        camera.camera = SCNCamera()

        camera.camera?.zFar = 150

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

        self.scene?.rootNode.addChildNode(camera)

    }

    

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

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

        

        let hue = CGFloat(arc4random() % 10) * 0.1

        box.firstMaterial?.diffuse.contents = UIColor(hue: hue, saturation: 0.6, brightness: 1.0, alpha: 1)

        let boxNode = SCNNode(geometry: box)

        boxNode.name = “box”

        boxNode.position = SCNVector3(x: 20, y: 50, z: 20)

        self.scene?.rootNode.addChildNode(boxNode)

        

        boxNode.physicsBody = SCNPhysicsBody.dynamicBody()

        boxNode.physicsBody?.velocity = SCNVector3(x: 0, y: 0, z: 50)

    }

    

    func renderer(aRenderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: NSTimeInterval) {

        let pole = scene.rootNode.childNodeWithName(“pole”, recursively: false)

        scene.rootNode.enumerateChildNodesUsingBlock { (node, p) -> Void in

            if node.name == “box” {

                let vx = –5.0 * node.presentationNode().position.x;

                let vz = –5.0 * node.presentationNode().position.z;

                let v = SCNVector3(x: vx, y: 3, z: vz)

                node.physicsBody?.applyForce(v, impulse: false)

                

                if node.presentationNode().position.y < –100 {

                    node.removeFromParentNode()

                }

            }

        }

    }

}