Lab 062 – First look at Gesture Component

A component that allows us to create unique SwiftUI gestures for RealityKit entities.

Overview

visionOS 26 brings us a new component called GestureComponent. This lets us create system gestures inline when creating entities and assigning components. This can be particularly useful when we have multiple entities that need to perform different actions using the same gesture.

// Create a gesture
let tapGesture = TapGesture()
  .onEnded({
    subjectToggle.toggle()
})

// Pass the gestutre to GestureComponent
let gestureComponent = GestureComponent(tapGesture)

// Add GestureComponent to the entity
subject.components.set(gestureComponent)

When we need a gesture that applies to all entities (or groups of entities), we can continue using the method introduced with visionOS 1.0. We have a whole section on System Gestures on Step Into Vision.

Lab Code

struct Lab062: View {

    @State private var subjectToggle = false

    var body: some View {
        RealityView { content in

            guard let scene = try? await Entity(named: "SwiftUIAnimationLab", in: realityKitContentBundle) else { return }
            content.add(scene)

            // Load the subject entity
            guard let subject = scene.findEntity(named: "Subject") else { return }

            // Create a gesture
            let tapGesture = TapGesture()
                .onEnded({
                    // Bonus: we'll use a SwiftUI animation to scale the entity
                    Entity.animate(.bouncy, body: {
                        subjectToggle.toggle()
                        let scaler: Float = subjectToggle ? 2.0 : 1.0
                        subject.scale = .init(repeating: scaler)
                    })
                })

            // Pass the gestutre to GestureComponent
            let gestureComponent = GestureComponent(tapGesture)

            // Add GestureComponent to the entity
            subject.components.set(gestureComponent)

        }
    }
}

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

Download the Xcode project with this and many more labs from Step Into Vision.

Questions or feedback?