首页 > 解决方案 > 在 ARKit 中将定向光定向到相机

问题描述

我试图放置一个朝向相机的定向光来模拟太阳(因为用户将相机指向太阳,然后按下按钮来放置定向光源)。

到目前为止,我已经尝试将相机视点的四元数共轭分配给灯光旋转。但是,这种方法似乎不起作用,并且产生的光的位置似乎相当随机。非常感谢任何有关通常如何处理的建议。这是我的代码:

 //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)

通过放置一个球体,我可以看到光线来自哪个方向:

 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)

标签: scenekitaugmented-realityarkitquaternionslight

解决方案


当您应该使用SCNConstraint. 将节点定向为始终指向当前相机的约束是SCNBillboardConstraint

对象会自动SCNBillboardConstraint调整节点的方向,使其局部 z 轴始终指向pointOfView当前用于渲染场景的节点。例如,您可以使用广告牌约束使用二维精灵图像而不是三维几何图形来有效地渲染场景的某些部分——通过将精灵映射到受广告牌约束影响的平面上,精灵保持其相对于观察者的方向.

let sunNode = SCNNode()
sunNode.light = SCNLight()
sunNode.light!.type = .directional
sunNode.light!.color = UIColor.yellow
sunNode.light!.intensity = 5000

let sunConstraint = SCNBillboardConstraint()
sunNode.constraints = [SCNBillboardConstraint()]
sunNode.constraints?.append(sunConstraint)

推荐阅读