Is it possible to have a SCNNode which is transparent, but which occludes any object behind it?

5.1k views Asked by At

So to be clear on my goals, since I don't have any code to share... Lets say I have a SCNNode which is positioned between the camera and another SCNNode. The first SCNNode is a SCNBox, but has no texture, thus the second SCNNode can be seen behind it. I want to give the first node a transparent material, but to have it also occlude all nodes behind it, as though it was opaque. In a regular scene, this would mean that you could see the scene background color, black perhaps, but I'm planning on doing this in ARKit, which makes more sense as that means you'd simply see the real world behind it.

2

There are 2 answers

0
Vasilii Muravev On BEST ANSWER

You can use material with clear color:

extension SCNMaterial {
    convenience init(color: UIColor) {
        self.init()
        diffuse.contents = color
    }
    convenience init(image: UIImage) {
        self.init()
        diffuse.contents = image
    }
}

let clearMaterial = SCNMaterial(color: .clear)
boxNode.materials = [clearMaterial]
0
Marco Boschi On

I've tested my idea from the comments and it seems to work, not be perfectly but I'll expand later on this point.

To support the rendering process SceneKit uses a depth buffer and render a point only if it will be in front of what is saved in said buffer so we have to tell SceneKit to render your see-through cube first then all the other nodes, so leave your cube node renderingOrder property to 0 (the default value) then set all the other nodes renderingOrder to a higher value, i.e. 1, 10... Normally for transparent objects you don't want to write to the depth buffer so you can see objects behind but it's not the case so leave your cube material writeToDepthBuffer property to true (the default value). Last thing to do is to make your cube transparent, you can use the default material and then add

cube.geometry?.firstMaterial?.transparency = 0.00000001

As I've said before this method is not perfect and it feels more of a workaround... but it works. The reason why we don't set the transparency to exactly 0 is that if we do so is like the cube is not even there, that is fully transparent pixel are not saved to the depth buffer.