Tap Gesture Basics

Using the system tap gesture with RealityKit.

We covered how to use SwiftUI Gestures with RealityKit Entities, now let’s take a look a Tap Gesture example. First we will set up a basic scene with three toys from the content library. When we tap on one of these toys we want to raise it up. Tapping it again should lower it back to the table.

The entities already have the Collision and Input Target components added in Reality Composer Pro. All we have to do is create a gesture and use it in the SwiftUI hierarchy. We will capture the “tapped” entity in a state variable whenever we tap on a toy. If something else is already selected, we will lower it before raising the new selection.

struct Example004: View {

    @State var selected: Entity? = nil

    var body: some View {
        RealityView { content in
            // Load the scene from the Reality Composer Pro project
            if let scene = try? await Entity(named: "GestureLabs") {
                content.add(scene)
            }
        }
        .gesture(tapExample)
        .realityViewLayoutBehavior(.fixedSize)
        .volumeBaseplateVisibility(.hidden)
    }

    var tapExample: some Gesture {
        TapGesture()
            .targetedToAnyEntity()
            .onEnded { value in
                
                if selected === value.entity {
                    // If the same entity is tapped, lower it and deselect.
                    selected?.position.y = 0
                    selected = nil
                } else {
                    // Lower the previously selected entity (if any).
                    selected?.position.y = 0

                    // Raise the new entity and select it.
                    value.entity.position.y = 0.1
                    selected = value.entity
                }
            }
    }
}

visionOS also supports a SpatialTapGesture which we can use to calculate a position for the tap on the entity.

We can adjust the number of taps it takes to fire the gesture. See: Multiple taps with TapGesture

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

Questions or feedback?