Tie SCNFloor to the AR object

Viewed 43

i added SCNFloor to the scene view to show a shadows, and it works, but there are two issues

1- When I add the first object, the floor seems below the object and it shows the shadows, but if I move the object, probably after 0.5 m in the real world distance, seems the floor will end at some point and there is no shadows after that point. That floor is not moving with the object

2- When I add a second object, there is no floor below it and the shadows only shows then I move the second object around the first object and then shadows appears.

First in the view did load

    let light = SCNLight()
    light.type = .directional
    light.shadowColor =  UIColor(white: 0, alpha: 0.5)
    light.color = UIColor.white
    light.castsShadow = true
    light.automaticallyAdjustsShadowProjection = true
    light.shadowMode = .deferred
    let sunLightNode = SCNNode()
    sunLightNode.position = SCNVector3(x: 1_000, y: 1_000, z: 0)
    sunLightNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w: .pi * 1.5)
    sunLightNode.light = light
    sceneView.scene.rootNode.addChildNode(sunLightNode)

And then, here the functions for floor and material

private func addFloorSCN(node: SCNNode, planeAnchor: ARPlaneAnchor) {
    let anchorX = planeAnchor.center.x
    let anchorY = planeAnchor.center.y
    let anchorZ = planeAnchor.center.z
    
    let floor = SCNFloor()
    let floorNode = SCNNode(geometry: floor)
    floorNode.position = SCNVector3(anchorX, anchorY, anchorZ)


    
    floor.length = CGFloat(planeAnchor.extent.z)
    floor.width = CGFloat(planeAnchor.extent.x)
    floor.reflectivity = 0
    floor.materials = [shadowMaterialStandard()]
    node.addChildNode(floorNode)
}


func shadowMaterialStandard() -> SCNMaterial {
    let material = SCNMaterial()
    material.lightingModel = .constant
    material.writesToDepthBuffer = true
    material.readsFromDepthBuffer = true
    material.colorBufferWriteMask = []
    return material
 }

And Finally, I called the addFloorSCN in the renderer(_:didAdd:for:)

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    guard anchor is ARPlaneAnchor else { return }
    guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
    addFloorSCN(node: node, planeAnchor: planeAnchor)
}

What is the issue here, could anyone help me on that please? Thank you so much

1 Answers
Related