2 // GameViewController.swift
5 // Created by Alan Knowles on 29/3/2022.
17 class GameViewController: UIViewController {
19 override func viewDidLoad() {
23 let scene = SCNScene(named: "art.scnassets/ship.scn")!
25 // create and add a camera to the scene
26 let cameraNode = SCNNode()
27 cameraNode.camera = SCNCamera()
28 scene.rootNode.addChildNode(cameraNode)
31 cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
33 // create and add a light to the scene
34 let lightNode = SCNNode()
35 lightNode.light = SCNLight()
36 lightNode.light!.type = .omni
37 lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
38 scene.rootNode.addChildNode(lightNode)
40 // create and add an ambient light to the scene
41 let ambientLightNode = SCNNode()
42 ambientLightNode.light = SCNLight()
43 ambientLightNode.light!.type = .ambient
44 ambientLightNode.light!.color = UIColor.darkGray
45 scene.rootNode.addChildNode(ambientLightNode)
47 // retrieve the ship node
48 let ship = scene.rootNode.childNode(withName: "ship", recursively: true)!
50 // animate the 3d object
51 ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1)))
53 // retrieve the SCNView
54 let scnView = self.view as! SCNView
56 // set the scene to the view
59 // allows the user to manipulate the camera
60 scnView.allowsCameraControl = true
62 // show statistics such as fps and timing information
63 scnView.showsStatistics = true
66 scnView.backgroundColor = UIColor.black
68 // add a tap gesture recognizer
69 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
70 scnView.addGestureRecognizer(tapGesture)
71 scnView.isHidden = true
76 func handleTap(_ gestureRecognize: UIGestureRecognizer) {
77 // retrieve the SCNView
78 let scnView = self.view as! SCNView
80 // check what nodes are tapped
81 let p = gestureRecognize.location(in: scnView)
82 let hitResults = scnView.hitTest(p, options: [:])
83 // check that we clicked on at least one object
84 if hitResults.count > 0 {
85 // retrieved the first clicked object
86 let result = hitResults[0]
89 let material = result.node.geometry!.firstMaterial!
92 SCNTransaction.begin()
93 SCNTransaction.animationDuration = 0.5
95 // on completion - unhighlight
96 SCNTransaction.completionBlock = {
97 SCNTransaction.begin()
98 SCNTransaction.animationDuration = 0.5
100 material.emission.contents = UIColor.black
102 SCNTransaction.commit()
105 material.emission.contents = UIColor.red
107 SCNTransaction.commit()
111 override var shouldAutorotate: Bool {
115 override var prefersStatusBarHidden: Bool {
119 override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
120 if UIDevice.current.userInterfaceIdiom == .phone {
121 return .allButUpsideDown