流程
- 1 . ARConfiguration(建議用ARWorldTrackingConfiguration負責追蹤相機的運動)
lazy var arSessionConfiguration:ARWorldTrackingConfiguration = {
let c = ARWorldTrackingConfiguration()
c.planeDetection = .horizontal //追蹤方向 目前就這一種
c.isLightEstimationEnabled = true//自適應燈光
return c
}()
- 2 . ARSession(負責管理相機追蹤配置及3D相機座標)
lazy var arSession: ARSession = {
let s = ARSession()
return s
}()
lazy var arSCNView: ARSCNView = {
let v = ARSCNView(frame: self.view.bounds)
v.delegate = self
v.session = self.arSession
v.automaticallyUpdatesLighting = true
return v
}()
//這個是swift的方法 OC方法 - (void)runWithConfiguration:(ARConfiguration *)configuration NS_SWIFT_UNAVAILABLE("Use run(_:options:) instead");
self.arSession.run(self.arSessionConfiguration, options: ARSession.RunOptions.resetTracking)
//獲取虛擬物體的場景 這個是系統自帶的小飛機 自己匯入素材的時候如果獲取場景失敗記得檢視 BuildPhase 的CopyBundleResource 新增上
guard let scene = SCNScene(named: "art.scnassets/ship.scn") else{return}
//AR世界萬物皆節點 -有位偉人這麼說過
//每個Scene中有且只有一個節點,裡面的所有物體都是其子節點!
let shipNode = scene.rootNode.childNodes.first!
//將這個節點新增到我們檢視的Scene中 位置預設是相機位置
//可以為其設定一個位置 其屬性 open var position: SCNVector3
arSCNView.scene.rootNode.addChildNode(shipNode)