I'm trying to place a directional light oriented towards the camera to simulate a sun (as in the user points the camera towards the sun, and presses a button to place the directional light source).
So far, I have tried to take the quaternion conjugate of the camera point of view and assigning it to the lights rotation. However, this method does not seem to work and the resulting position of the light seems fairly random. Any suggestion on how this usually would be handled is greatly appreciated. This is my code:
//Disable the default lightning updates
sceneView.autoenablesDefaultLighting = false
sceneView.automaticallyUpdatesLighting = false
var sunLight = SCNLight()
sunLight.intensity = 1000
sunLight.type = .directional
sunLight.color = UIColor.white
sunLight.castsShadow = true
sunLight.shadowMode = .forward
sunLight.automaticallyAdjustsShadowProjection = true
var sunNode = SCNNode()
sunNode.light = sunLight
sunNode.castsShadow = true
guard let cameraNode = self.sceneView.pointOfView else { return }
let q = cameraNode.orientation
let qConjugate = SCNVector4(x: -q.x, y: -q.y, z: -q.z, w: q.w)
sunNode.rotation = qConjugate
sceneView.scene.rootNode.addChildNode(sunNode)
By placing a sphere I can see from which direction the light is coming from:
let sphere = SCNSphere(radius: 0.3)
sphere.firstMaterial?.diffuse.contents = UIColor.green.withAlphaComponent(1)
let sphereNode = SCNNode(geometry: sphere)
sphereNode.position = SCNVector3(0,0,0)
sceneView.scene.rootNode.addChildNode(sphereNode)