Search code examples
iosswiftlightingrealitykit

Adding a Point Light in RealityKit


I have a very simple RealityKit scene (without AR) with a box on it. While the sides of the box are colored (I assume due to a default light), the front face is black. So I decided to add a point light at camera's position (based on other StackOverflow answers, and same anchor than the box one), but the box remains black. What am I missing ?

override func viewDidLoad() {
        super.viewDidLoad()
        
        myARView.environment.background = .color(.black)

        let anchor = AnchorEntity()
        myARView.scene.anchors.append(anchor)
        
        let box = MeshResource.generateBox(size: 0.3) // Generate mesh
        let material = SimpleMaterial(color: .blue, isMetallic: true)

        let entity = ModelEntity(mesh: box, materials: [material])
        entity.name="My Box"
        entity.generateCollisionShapes(recursive: true)
        entity.position=SIMD3(x: 0.2, y: 0.8, z: -1)
        anchor.addChild(entity)
        
        let pointLight = PointLight()
        pointLight.light.color = .red
        pointLight.light.intensity = 15000000
        pointLight.light.attenuationRadius = 7.0
        pointLight.position = myARView.cameraTransform.translation // 0, 0, 2
        
        anchor.addChild(pointLight)
    }

enter image description here


Solution

  • There's a couple of things here, the most noticeable is that your material is set to .blue, and you're trying to light it using a .red light. The material's made from the colour contains zero red (in rgb form), so the light will have no effect on it. If you're using glasses with a red filter on them, green and blue will just appear black, only the reds will shine through.

    Even if you change it to a .white light, it won't look much different though. This is just what it looks like with the default SimpleMaterial with isMetallic set to true; all you'll see is reflections of light, rather than see a light hitting it.

    This is because the roughness of the material is set to 0, increase it just a tiny bit you'll see the cube light up with your point light.

    var material = SimpleMaterial(color: .blue, isMetallic: true)
    material.roughness = 0.1
    

    Also worth noting, your light intensity is quite high, I assume this is just because you weren't seeing an effect before!