Lab 011 – Playing with Occlusion Material

Making myself a little fort and playing with occlusion material.

Just a bit of fun today. I felt like making myself a sad beige box to escape from the world. But what if I need to check on things?

Hiding inside a box and using an occlusion material sphere to peak outside

struct Lab011: View {

    @State var subjectEntity: Entity? = nil

    var body: some View {
        RealityView { content, attachments in

            if let scene = try? await Entity(named: "Lab011Scene", in: realityKitContentBundle) {
                content.add(scene)

                if let subject = scene.findEntity(named: "Subject") {

                    let mat = OcclusionMaterial()
                    subject.components[ModelComponent.self]?.materials[0] = mat
                    subject.isEnabled = false
                    subjectEntity = subject
                }

            }

        } update: { content, attachments in

        } attachments: {

        }
        .gesture(tapExample)
        .gesture(dragGesture)
    }

    var tapExample: some Gesture {
        TapGesture()
            .targetedToAnyEntity() 
            .onEnded { value in
                if(value.entity.name == "Wall_2") {
                    subjectEntity?.isEnabled = !subjectEntity!.isEnabled
                }
            }
    }

    var dragGesture: some Gesture {
        DragGesture()
            .targetedToAnyEntity()
            .onChanged { value in
                if(value.entity.name == "Subject") {
                    let newPost = value.convert(value.location3D, from: .local, to: .scene)
                    value.entity.position.x = min(max(newPost.x, -0.8), 0.8)
                    value.entity.position.y = min(max(newPost.y, 0.2), 1.8)
                }
            }
            .onEnded { value in
                // do something
            }
    }
}

Support our work so we can continue to bring you new examples and articles.

Questions or feedback?