
キューブにお絵かきするiPadアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var sceneView : SCNView?
var animationCount = 0
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
createCube()
createCamera()
createLight()
}
func setupScene() {
let sv = SCNView(frame: view.bounds)
sv.backgroundColor = UIColor(hue: 0.5, saturation: 0.1, brightness: 1, alpha: 1)
sv.scene = SCNScene()
view.addSubview(sv)
sceneView = sv
}
func createCube() {
let cube = SCNBox(width: 10, height: 10, length: 10, chamferRadius: 1)
cube.firstMaterial?.diffuse.contents = UIColor(white: 0.98, alpha: 1)
let cubeNode = SCNNode(geometry: cube)
cubeNode.name = “cube”
sceneView?.scene?.rootNode.addChildNode(cubeNode)
let words = [“A”,“B”,“1”,“2”]
for (i, w) in enumerate(words) {
let sceneText = SCNText(string: w, extrusionDepth: 0.2)
sceneText.font = UIFont.boldSystemFontOfSize(8)
sceneText.firstMaterial?.diffuse.contents = UIColor.lightGrayColor()
let textNode = SCNNode(geometry: sceneText)
textNode.pivot = SCNMatrix4Translate(textNode.transform, 4, 4, –5)
textNode.transform = SCNMatrix4Rotate(textNode.transform, Float(M_PI * 0.5) * Float(i), 0, 1, 0)
cubeNode.addChildNode(textNode)
}
}
func createCamera() {
let camera = SCNNode()
camera.camera = SCNCamera()
camera.position = SCNVector3(x: 0, y: 0, z: 20)
sceneView?.scene?.rootNode.addChildNode(camera)
}
func createLight() {
let light = SCNLight()
light.type = SCNLightTypeOmni
light.color = UIColor(white: 0.99, alpha: 1)
let lightNode = SCNNode()
lightNode.light = light
lightNode.position = SCNVector3(x: 0, y: 0, z: 50)
sceneView?.scene?.rootNode.addChildNode(lightNode)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if touches.count == 1 && animationCount == 0 {
let p = touches.anyObject()!.locationInView(sceneView)
if let hit = sceneView?.hitTest(p, options: [SCNHitTestSortResultsKey:true])?.filter({ $0.node.name == “cube” }).first as? SCNHitTestResult {
dotAtPoint(hit.localCoordinates)
} else {
animationCount += 1
let cube = sceneView?.scene?.rootNode.childNodeWithName(“cube”, recursively: false)
cube?.runAction(SCNAction.rotateByX(0, y: –CGFloat(M_PI) * 0.5, z: 0, duration: 0.5), completionHandler: { self.animationCount -= 1
})
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
if touches.count == 1 && animationCount == 0 {
let p = touches.anyObject()!.locationInView(sceneView)
if let hit = sceneView?.hitTest(p, options: [SCNHitTestSortResultsKey:true])?.filter({ $0.node.name == “cube” }).first as? SCNHitTestResult {
dotAtPoint(hit.localCoordinates)
}
}
}
func dotAtPoint(p : SCNVector3) {
let cube = sceneView?.scene?.rootNode.childNodeWithName(“cube”, recursively: false)
let dot = SCNBox(width: 0.3, height: 0.3, length: 0.3, chamferRadius: 0)
dot.firstMaterial?.diffuse.contents = UIColor.blackColor()
let dotNode = SCNNode(geometry: dot)
dotNode.position = p;
cube?.addChildNode(dotNode)
}
}