
箱なのか、箱と箱の隙間なのかという錯視を表示する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.scene = SCNScene()
view.addSubview(sv)
sceneView = sv
}
func createBox() {
let wall = SCNNode()
wall.name = “wall”
self.sceneView?.scene?.rootNode.addChildNode(wall)
[Int](0…100).each { i in
let box = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0)
box.materials = {
var materials = [SCNMaterial]();
[UIColor.lightGrayColor(), UIColor.darkGrayColor(), UIColor.blackColor(), UIColor.blackColor(), UIColor.darkGrayColor(), UIColor.blackColor()].each { color in
let m = SCNMaterial()
m.diffuse.contents = color
materials.append(m)
}
return materials
}()
let bNode = SCNNode(geometry: box)
var x = Float(i % 10) * sqrt(2.0)
var y = Float(i / 10)
if y % 2 == 0 {
x += 0.5 * sqrt(2.0)
}
bNode.position = SCNVector3(x: x, y: y, z: -y * 0.5 * sqrt(2.0))
bNode.rotation = SCNVector4(x: 0, y: 1, z: 0, w: Float(M_PI/4.0))
wall.addChildNode(bNode)
}
}
func createCamera() {
let camera = SCNNode()
camera.name = “camera”
camera.camera = SCNCamera()
camera.camera?.usesOrthographicProjection = true
camera.camera?.orthographicScale = 2.0
camera.position = SCNVector3(x: 6, y: 5, z: 10)
self.sceneView?.scene?.rootNode.addChildNode(camera)
}
var count = 0
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let camera = sceneView?.scene?.rootNode.childNodeWithName(“camera”, recursively: false)
if count != 0 {
camera?.runAction(SCNAction.rotateByAngle(CGFloat(M_PI), aroundAxis: SCNVector3(x: 0, y: 0, z: 1), duration: 1.0))
return
}
let wall = self.sceneView?.scene?.rootNode.childNodeWithName(“wall”, recursively: false)
wall?.runAction(SCNAction.rotateByAngle(CGFloat(-M_PI/6.0), aroundAxis: SCNVector3(x: 1, y: 0, z: 0), duration: 0.5))
++count
}
}
extension Array {
func each(doit:T -> Void) { for i in self { doit(i) }}
}