
サボテンのトゲをポチるiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var sceneView : SCNView?
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
createCactus()
createCamera()
}
func setupScene() {
let sv = SCNView(frame: view.bounds)
sv.scene = SCNScene()
sv.backgroundColor = UIColor(hue: 0.14, saturation: 0.7, brightness: 1, alpha: 1)
sv.autoenablesDefaultLighting = true
sv.allowsCameraControl = true
view.addSubview(sv)
sceneView = sv
}
func createCactus() {
let cactus = SCNCapsule(capRadius: 3, height: 10)
cactus.firstMaterial?.diffuse.contents = UIColor(hue: 0.3, saturation: 0.7, brightness: 0.8, alpha: 1)
let cactusNode = SCNNode(geometry: cactus)
sceneView?.scene?.rootNode.addChildNode(cactusNode)
var w : Float = 0.0
[Int](0…47).each { i in
let thorn = SCNCylinder(radius: 0.2, height: 8)
thorn.firstMaterial?.diffuse.contents = UIColor(hue: 0.3, saturation: 0.8, brightness: 0.75, alpha: 1)
let node = SCNNode(geometry: thorn)
node.name = “thorn”
node.pivot = SCNMatrix4Rotate(node.transform, Float(M_PI)/2.0, 1, 0, 0)
let x = 1.5 * cos(w)
let y = i / 6 – 4
let z = 1.5 * sin(w)
node.transform = SCNMatrix4Translate(node.transform, 0, Float(y), 0)
node.transform = SCNMatrix4Rotate(node.transform, w, 0, 1, 0)
self.sceneView?.scene?.rootNode.addChildNode(node)
w = w + Float(M_PI) / 6.0
}
}
func createCamera() {
let camera = SCNNode()
camera.camera = SCNCamera()
camera.position = SCNVector3(x: 0, y: 0, z: 20)
self.sceneView?.scene?.rootNode.addChildNode(camera)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let p = touches.anyObject()!.locationInView(sceneView)
if let hit = sceneView?.hitTest(p, options: [SCNHitTestSortResultsKey : true])?.first as? SCNHitTestResult {
if hit.node.name == “thorn” {
hit.node.runAction(SCNAction.scaleTo(0, duration: 1.0))
}
}
}
}
extension Array {
func each(doit:T -> Void) { for i in self { doit(i); }}
}