
3Dのテキストの周りをカメラでくるっと一周するiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController, SCNSceneRendererDelegate {
weak var scene : SCNScene?
weak var timer : NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.orangeColor()
self.setupScene()
self.setupObject()
self.setupLight()
self.setupCamera()
}
func setupScene()
{
var w = CGRectGetMaxX(self.view.bounds)
var sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: w, height: w))
sceneView.center = CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds))
sceneView.delegate = self;
self.view.addSubview(sceneView)
sceneView.scene = SCNScene()
sceneView.backgroundColor = UIColor.brownColor()
self.scene = sceneView.scene
}
func setupObject()
{
for i in 0..<3 {
var text = SCNText(string: “Camera Test”, extrusionDepth: 5)
text.font = UIFont.boldSystemFontOfSize(15.0)
var textNode = SCNNode(geometry: text)
if i==1 { textNode.name = “text” }
textNode.position = SCNVector3(x: 0, y: Float((i-1) * 20), z: 0)
textNode.rotation = SCNVector4(x: 0, y: 1, z: 1, w: 0.8 * Float(i))
self.scene?.rootNode.addChildNode(textNode)
var min = SCNVector3(x: 0, y: 0, z: 0)
var max = SCNVector3(x: 0, y: 0, z: 0)
if textNode.getBoundingBoxMin(&min, max:&max) {
textNode.pivot = SCNMatrix4MakeTranslation((max.x + min.x) * 0.5, 0, 0);
}
}
}
func setupLight()
{
var light = SCNLight()
light.type = SCNLightTypeSpot
light.color = UIColor.redColor()
var spot = SCNNode()
spot.light = light
spot.position = SCNVector3(x: 0, y: 0, z: 250)
self.scene?.rootNode.addChildNode(spot)
}
func setupCamera()
{
var cameraNode = SCNNode()
cameraNode.name = “camera”
cameraNode.camera = SCNCamera()
cameraNode.camera?.zFar = 200
cameraNode.position = SCNVector3(x: 30, y: 0, z: 100)
if let target = self.scene?.rootNode.childNodeWithName(“text”, recursively: false) {
cameraNode.constraints = [SCNLookAtConstraint(target: target)]
}
self.scene?.rootNode.addChildNode(cameraNode)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector(“tick”), userInfo: nil, repeats: true)
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
self.timer?.invalidate()
}
var angle = Float(M_PI/2.0)
func tick()
{
if let camera = self.scene?.rootNode.childNodeWithName(“camera”, recursively: false) {
camera.position = SCNVector3(x: Float(100 * cos(angle)), y: 0, z: Float(100 * sin(angle)))
angle = angle + Float(M_PI/30.0)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}