
球で作ったわっかの中でキューブがはねるiPhoneアプリ(Swift)のサンプルコードを描いてみます。
import UIKit
import SceneKit
class ViewController: UIViewController {
weak var sceneView : SCNView?
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
createRing()
createClearWall()
createBlock()
createCamera()
}
func setupScene() {
let sv = SCNView(frame: view.bounds)
sv.scene = SCNScene()
sv.backgroundColor = UIColor(hue: 0.5, saturation: 0.7, brightness: 1, alpha: 1);
view.addSubview(sv)
sv.allowsCameraControl = true
sv.autoenablesDefaultLighting = true
sceneView = sv
}
func createRing() {
let ring = SCNNode()
ring.name = “ring”
let dw = M_PI / 4.0
let r = 4.0
for i in 0…8 {
let x = r * cos(dw * Double(i))
let y = r * sin(dw * Double(i))
let ball = SCNSphere(radius: 0.5)
ball.firstMaterial?.diffuse.contents = UIColor(hue: 0.1 * CGFloat(i), saturation: 0.5, brightness: 1, alpha: 1)
let ballNode = SCNNode(geometry: ball)
ballNode.position = SCNVector3Make(Float(x), Float(y), 0)
ring.addChildNode(ballNode)
}
sceneView?.scene?.rootNode.addChildNode(ring)
ring.physicsBody = SCNPhysicsBody.dynamicBody()
ring.physicsBody?.restitution = 1.0
let j = SCNPhysicsHingeJoint(body: ring.physicsBody!, axis: SCNVector3(x: 0, y: 0, z: 1), anchor: SCNVector3Zero)
sceneView?.scene?.physicsWorld.addBehavior(j)
}
func createBlock() {
let block = SCNBox(width: 2.2, height: 2.2, length: 2, chamferRadius: 0.4)
block.firstMaterial?.diffuse.contents = UIColor.redColor()
let blockNode = SCNNode(geometry: block)
blockNode.physicsBody = SCNPhysicsBody.dynamicBody()
sceneView?.scene?.rootNode.addChildNode(blockNode)
}
func createClearWall() {
for i in 0…1 {
let w = SCNBox(width: 10, height: 10, length: 0.1, chamferRadius: 0)
w.firstMaterial?.diffuse.contents = UIColor.clearColor()
let wNode = SCNNode(geometry: w)
let z = (i == 0) ? 1.2 : –1.2
wNode.position = SCNVector3(x: 0, y: 0, z: Float(z))
sceneView?.scene?.rootNode.addChildNode(wNode)
wNode.physicsBody = SCNPhysicsBody.staticBody()
}
}
func createCamera() {
let camera = SCNNode()
camera.camera = SCNCamera()
camera.position = SCNVector3(x: 0, y: 0, z: 20)
sceneView?.scene?.rootNode.addChildNode(camera)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let ring = sceneView?.scene?.rootNode.childNodeWithName(“ring”, recursively: false) {
ring.physicsBody?.applyTorque(SCNVector4(x: 0, y: 0, z: 1, w: 20), impulse: true)
}
}
}