SceneKit to show 3D content in Swift 5

— In this history, I going to show how easy was show 3D content with SceneKit framework using high-level scene descriptions.

 

This means that we can use SceneKit for easy things (normal development), and Metal or OpenGL to make high-level customization e.g.: Games or for a high level of images manipulation.

In addition, there is little documentation to use the metal and OpenGL, adding its complexity of use.

fter putting ourselves in context and getting the theory, it’s time for the code 💻...

 

I will show how to open .obj files, although SceneKit it is able to open more kinds of files like a .dae.blend, .scn…

So, open Xcode… Create new project… Select Single View App…

⌨ TIME FOR CODING…

 

import UIKit
import SceneKit

class ViewController: UIViewController {
    
    @IBOutlet weak var sceneView: SCNView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1: Load .obj file
        let scene = SCNScene(named: "converse_obj.obj")
        
        // 2: Add camera node
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        // 3: Place camera
        cameraNode.position = SCNVector3(x: 0, y: 10, z: 35)
        // 4: Set camera on scene
        scene?.rootNode.addChildNode(cameraNode)
        
        // 5: Adding light to scene
        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light?.type = .omni
        lightNode.position = SCNVector3(x: 0, y: 10, z: 35)
        scene?.rootNode.addChildNode(lightNode)
        
        // 6: Creating and adding ambien light to scene
        let ambientLightNode = SCNNode()
        ambientLightNode.light = SCNLight()
        ambientLightNode.light?.type = .ambient
        ambientLightNode.light?.color = UIColor.darkGray
        scene?.rootNode.addChildNode(ambientLightNode)
        
        // If you don't want to fix manually the lights
//        sceneView.autoenablesDefaultLighting = true
        
        // Allow user to manipulate camera
        sceneView.allowsCameraControl = true
        
        // Show FPS logs and timming
        // sceneView.showsStatistics = true
        
        // Set background color
        sceneView.backgroundColor = UIColor.white
        
        // Allow user translate image
        sceneView.cameraControlConfiguration.allowsTranslation = false
        
        // Set scene settings
        sceneView.scene = scene
        
    }
    
    
}

Step by step explanation

  

 

👁 The basic UI

CONCLUSION

posted on 2021-05-18 20:03  youhui  阅读(248)  评论(0)    收藏  举报