
3枚のコインをトスするiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var sceneView : SCNView?
override func viewDidLoad() {
super.viewDidLoad()
self.setupScene()
self.createDesk()
self.createCoins()
self.createCamera()
}
func setupScene() {
let sv = SCNView(frame: self.view.bounds)
sv.backgroundColor = UIColor(hue: 0.6, saturation: 0.2, brightness: 1, alpha: 1);
sv.scene = SCNScene()
self.view.addSubview(sv)
self.sceneView = sv
}
func createDesk() {
let desk = SCNBox(width: 40, height: 1, length: 15, chamferRadius: 0)
desk.firstMaterial?.diffuse.contents = UIColor(hue: 0.13, saturation: 0.8, brightness: 0.6, alpha: 1)
let deskNode = SCNNode(geometry: desk)
deskNode.physicsBody = SCNPhysicsBody.staticBody()
self.sceneView?.scene?.rootNode.addChildNode(deskNode)
}
func createCoins() {
for i in 0..<3 {
let coin = SCNCylinder(radius: 4, height: 0.3)
let m0 = SCNMaterial()
m0.diffuse.contents = UIColor(hue: 0.1, saturation: 0.4, brightness: 1, alpha: 1)
let m1 = SCNMaterial()
m1.diffuse.contents = UIColor(hue: 0.4, saturation: 0.4, brightness: 1, alpha: 1)
let m2 = SCNMaterial()
m2.diffuse.contents = UIColor(hue: 0.7, saturation: 0.4, brightness: 1, alpha: 1)
coin.materials = [m0, m1, m2]
let coinNode = SCNNode(geometry: coin)
coinNode.name = “coin”
coinNode.position = SCNVector3(x: –12 + Float(i) * 12, y: 2, z: 0)
coinNode.physicsBody = SCNPhysicsBody.dynamicBody()
coinNode.physicsBody?.velocityFactor = SCNVector3(x: 0, y: 1, z: 0)
self.sceneView?.scene?.rootNode.addChildNode(coinNode)
}
}
func createCamera() {
let camera = SCNNode()
camera.camera = SCNCamera()
camera.position = SCNVector3(x: 0, y: 30, z: 70)
camera.rotation = SCNVector4(x: 1, y: 0, z: 0, w: –0.3)
self.sceneView?.scene?.rootNode.addChildNode(camera)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let p = touches.anyObject()!.locationInView(self.sceneView)
if let hit = self.sceneView?.hitTest(p, options: [SCNHitTestSortResultsKey : true])?.first?.node {
if hit.name == “coin” {
hit.physicsBody?.applyForce(SCNVector3(x: 0, y: 20, z: 0), atPosition: SCNVector3(x: 0, y: 0, z: 1.5), impulse: true)
}
}
}
}