Book Image

Swift by Example

By : Giordano Scalzo
Book Image

Swift by Example

By: Giordano Scalzo

Overview of this book

Table of Contents (15 chapters)

Flying in a 3D world


Let's now build a scene where we can fly, by skipping colorful cubes.

Setting up the scene

By running the app built so far, you might have noticed that on selecting the Play button, the app crashes. This is because GameViewController expects to be set up by the storyboard where the view is actually an SCNView, and because the view is a plain UIView, it crashes.

To fix this issue, we need to build a slim GameViewController from scratch:

import UIKit
import QuartzCore
import SceneKit

class GameViewController: UIViewController {
    private let scnView = SCNView()
    private var scene: SCNScene!

    override func viewDidLoad() {
        super.viewDidLoad()
        scnView.frame = view.bounds
        view.addSubview(scnView)
        
        createContents()
    }
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

The createContents() function creates all the elements of the game, and it'll be handy to have it as a separate function when we...