緑色のピラミッドで木を作るiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var sceneView : SCNView?
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
createGround()
createCamera()
createLight()
createTree(SCNVector3(x: 0, y: 10, z: 0))
}
func setupScene() {
let sv = SCNView(frame: self.view.bounds)
sv.backgroundColor = UIColor(hue: 0.5, saturation: 0.05, brightness: 1, alpha: 1)
sv.scene = SCNScene()
view.addSubview(sv)
sceneView = sv
}
func createGround() {
let ground = SCNBox(width: 50, height: 2, length: 50, chamferRadius: 0)
ground.firstMaterial?.diffuse.contents = UIColor(hue: 0.1, saturation: 0.5, brightness: 0.4, alpha: 1)
let groundNode = SCNNode(geometry: ground)
groundNode.physicsBody = SCNPhysicsBody.staticBody()
sceneView?.scene?.rootNode.addChildNode(groundNode)
}
func createCamera() {
let camera = SCNNode()
camera.camera = SCNCamera()
camera.camera?.zFar = 120
camera.position = SCNVector3(x: 0, y: 30, z: 80)
camera.rotation = SCNVector4(x: 1, y: 0, z: 0, w: –0.2)
sceneView?.scene?.rootNode.addChildNode(camera)
}
func createLight() {
let light = SCNLight()
light.type = SCNLightTypeDirectional
let lightNode = SCNNode()
lightNode.light = light
lightNode.position = SCNVector3(x: 0, y: 30, z: 100)
lightNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: –0.4)
self.sceneView?.scene?.rootNode.addChildNode(lightNode)
}
func createTree(p : SCNVector3) {
let treeNode = SCNNode()
treeNode.position = p
sceneView?.scene?.rootNode.addChildNode(treeNode)
let trunk = SCNCylinder(radius: 1, height: 8)
trunk.firstMaterial?.diffuse.contents = UIColor(hue: 0.15, saturation: 0.5, brightness: 0.6, alpha: 1)
let trunkNode = SCNNode(geometry: trunk)
treeNode.addChildNode(trunkNode)
for i in 0..<3 {
let brunch = SCNPyramid(width: 8 – CGFloat(i), height: 6, length: 8 – CGFloat(i))
brunch.firstMaterial?.diffuse.contents = UIColor(hue: 0.4, saturation: 0.3, brightness: 0.8, alpha: 1)
let brunchNode = SCNNode(geometry: brunch)
brunchNode.position = SCNVector3(x: 0, y: 3 * Float(i), z: 0)
let angle = 2.0 * Float(M_PI) * Float(arc4random_uniform(10)) * 0.1
brunchNode.transform = SCNMatrix4Rotate(brunchNode.transform, angle, 0, 1, 0)
treeNode.addChildNode(brunchNode)
}
treeNode.physicsBody = SCNPhysicsBody.dynamicBody()
treeNode.physicsBody?.angularVelocityFactor = SCNVector3(x: 0, y: 0, z: 0)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let x = Float(arc4random_uniform(40)) – 20
let z = Float(arc4random_uniform(40)) – 20
let p = SCNVector3(x: x, y: 10, z: z)
createTree(p)
}
}