Lab 018 – Pulling an entity out of the ground

Using occlusion material to hide an entity under the users ground or floor.

One of my favorite uses of occlusion material is to hide entities behind it until a certain action or event. To demonstrate, this scene in Reality Composer Pro has a Rocket entity and a cube. I scaled the cube to fill a few meters around the users floor, then hid most of the rocket below it. I swapped out the default material with a version that uses one of the occlusion nodes.

A screenshot from Reality Composer Pro

The code for this lab just sets up the scene and adds a Y axis-only drag gesture so we can pull the rocker out of the ground.

struct Lab018: View {
    var body: some View {
        RealityView { content in

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

        }
        .modifier(DragGestureLab018())
    }
}

fileprivate struct DragGestureLab018: ViewModifier {

    @State var isDragging: Bool = false
    @State var initialPosition: SIMD3<Float> = .zero

    func body(content: Content) -> some View {
        content
            .gesture(
                DragGesture()
                    .targetedToAnyEntity()
                    .onChanged { value in

                        if !isDragging {
                            isDragging = true
                            initialPosition = value.entity.position
                        }

                        // Only move on Y, within a set range
                        let movement = value.convert(value.gestureValue.translation3D, from: .local, to: .scene)
                        let clampedY = min(max(initialPosition.y + movement.y, -1.06), 2.2)
                        let yOnlyMovement = SIMD3<Float>(initialPosition.x, clampedY, initialPosition.z)

                        value.entity.position = yOnlyMovement

                    }
                    .onEnded { value in
                        isDragging = false
                        initialPosition = .zero
                    }
            )
    }
}

Video demo

A video demo of an entity being hidden underneath occlusion material

We could greatly expand on this with ARKit to apply this effect to other surfaces beyond the floor.

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

Questions or feedback?