サイコロをふるiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var scene : SCNScene?
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.createDice()
self.createPlate()
self.createCamera()
}
func setup()
{
var scene = SCNScene()
var sceneView = SCNView(frame: self.view.bounds)
sceneView.backgroundColor = UIColor(hue: 0.5, saturation: 0.8, brightness: 0.8, alpha: 1)
sceneView.scene = scene
self.view.addSubview(sceneView)
self.scene = scene
self.scene?.physicsWorld.speed = 5;
}
var dotpattern = [[5], [3,7], [3,5,7], [1,3,7,9], [1,3,7,5,9], [1,3,4,6,7,9]]
func createDice()
{
var materials: [SCNMaterial] = []
for n in 1…6 {
var face = CALayer()
face.frame = CGRectMake(0, 0, 600, 600)
face.backgroundColor = UIColor.whiteColor().CGColor
var dots = CAShapeLayer()
var path = UIBezierPath()
for p in dotpattern[n – 1] {
var x = ((p-1) % 3) * 160 + 140
var y = ((p-1) / 3) * 160 + 140
var point = CGPoint(x: x, y: y)
path.appendPath(UIBezierPath(arcCenter: point, radius: 90.0, startAngle: 0, endAngle:CGFloat(2.0 * M_PI), clockwise: false))
}
dots.path = path.CGPath
dots.fillColor = UIColor.blackColor().CGColor
face.addSublayer(dots)
var material = SCNMaterial()
material.diffuse.contents = face;
materials += [material]
}
var box = SCNBox(width: 10, height: 10, length: 10, chamferRadius: 2)
box.materials = materials;
var node = SCNNode(geometry: box)
node.name = “dice”
self.scene?.rootNode.addChildNode(node)
node.physicsBody = SCNPhysicsBody.dynamicBody()
}
func createPlate() {
var plate = SCNBox(width: 40, height: 2, length: 40, chamferRadius: 0)
plate.firstMaterial?.diffuse.contents = UIColor.brownColor()
var node = SCNNode(geometry: plate)
node.position = SCNVector3(x: 0, y: –30, z: 0)
self.scene?.rootNode.addChildNode(node)
node.physicsBody = SCNPhysicsBody.staticBody()
}
func createCamera()
{
var cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.camera?.zFar = 200
cameraNode.position = SCNVector3(x: 0, y: 10, z: 100)
self.scene?.rootNode.addChildNode(cameraNode)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if let dice = self.scene?.rootNode.childNodeWithName(“dice”, recursively: false) {
dice.physicsBody?.applyForce(SCNVector3(x: 0, y: 10, z: 0), atPosition: SCNVector3(x: 5, y: 5, z: 5), impulse: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}