-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSunARViewController
More file actions
79 lines (60 loc) · 2.57 KB
/
Copy pathSunARViewController
File metadata and controls
79 lines (60 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import UIKit
import ARKit
import CoreLocation
class ViewController: UIViewController, ARSCNViewDelegate, CLLocationManagerDelegate {
let arView = ARSCNView()
let locationManager = CLLocationManager()
var sunNode: SCNNode?
override func viewDidLoad() {
super.viewDidLoad()
// AR setup
arView.frame = view.bounds
arView.delegate = self
view.addSubview(arView)
// Request location
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
// Set up AR scene
let configuration = ARWorldTrackingConfiguration()
arView.session.run(configuration)
// Initial render of the sun
renderSun()
}
func renderSun() {
guard let currentLocation = locationManager.location else { return }
let sunData = SunCalculation.sun(date: Date(), latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
let sunPosition = positionFromAzimuthAndAltitude(azimuth: sunData.azimuth, altitude: sunData.altitude)
if sunNode == nil {
sunNode = SCNNode(geometry: SCNSphere(radius: 0.05))
sunNode?.geometry?.firstMaterial?.diffuse.contents = UIColor.yellow
arView.scene.rootNode.addChildNode(sunNode!)
}
sunNode?.position = sunPosition
}
func positionFromAzimuthAndAltitude(azimuth: Double, altitude: Double) -> SCNVector3 {
let azimuthRadians = azimuth * .pi / 180.0
let altitudeRadians = altitude * .pi / 180.0
let x = cos(altitudeRadians) * cos(azimuthRadians)
let y = sin(altitudeRadians)
let z = cos(altitudeRadians) * sin(azimuthRadians)
return SCNVector3(x, y, z)
}
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
renderSun()
}
func updateSunPosition() {
renderSun() // Calculate and update sun's position
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
arView.session.pause()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Only reset tracking if necessary; this provides a smoother experience for the user.
let configuration = ARWorldTrackingConfiguration()
arView.session.run(configuration, options: [.removeExistingAnchors])
updateSunPosition() // Calculate and update sun's position every time the view appears
}
}