床に落っことして箱を開けて楽しむiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var scene : SCNScene?
override func viewDidLoad() {
super.viewDidLoad()
self.setupScene()
self.createBoard()
self.createCamera()
self.createLight()
}
func setupScene()
{
var sv = SCNView(frame: self.view.bounds)
sv.backgroundColor = UIColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 1)
sv.scene = SCNScene()
self.view.addSubview(sv)
self.scene = sv.scene
}
func createBoard()
{
var box = SCNBox(width: 20, height: 2, length: 20, chamferRadius: 0.2)
box.firstMaterial?.diffuse.contents = UIColor(red: 0.8, green: 0.8, blue: 0.2, alpha: 1)
var board = SCNNode(geometry: box)
self.scene?.rootNode.addChildNode(board)
board.physicsBody = SCNPhysicsBody.staticBody()
}
func createCamera()
{
var camera = SCNNode()
camera.camera = SCNCamera()
camera.position = SCNVector3(x: 0, y: 10, z: 40)
self.scene?.rootNode.addChildNode(camera)
}
func createLight()
{
var light = SCNLight()
light.type = SCNLightTypeOmni
light.color = UIColor.whiteColor()
var lightNode = SCNNode()
lightNode.light = light
lightNode.position = SCNVector3(x: 50, y: 40, z: 60)
self.scene?.rootNode.addChildNode(lightNode)
}
func createBoxes(point :SCNVector3)
{
for i in 0…6 {
var plane = SCNBox(width: 1.8, height: 1.8, length: 0.2, chamferRadius: 0)
plane.firstMaterial?.diffuse.contents = UIColor.brownColor()
var n = SCNNode(geometry: plane)
if (i == 0 || i == 1) {
n.transform = SCNMatrix4Rotate(n.transform, Float(M_PI)*0.5, 0, 1, 0)
n.position = SCNVector3(x: i == 0 ? 1 : –1, y:0, z: 0)
} else if (i == 2 || i == 3) {
n.transform = SCNMatrix4Rotate(n.transform, Float(M_PI)*0.5, 1, 0, 0)
n.position = SCNVector3(x:0, y: i == 2 ? 1 : –1, z: 0)
} else {
n.position = SCNVector3(x:0, y:0, z: i == 4 ? 1 : –1)
}
self.scene?.rootNode.addChildNode(n)
n.transform = SCNMatrix4Translate(n.transform, point.x, point.y, point.z)
n.physicsBody = SCNPhysicsBody.dynamicBody()
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var p = touches.anyObject()!.locationInView(self.view)
var maxx = CGRectGetMaxX(self.view.bounds)
var maxy = CGRectGetMaxY(self.view.bounds)
self.createBoxes(SCNVector3(x: Float(p.x – maxx/2.0) * 0.05, y: 20, z: 0))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}