Goal : Drag a sphere across the room and track it's position
Problem: The gesture seems to have no effect on the sphere ModelEntity. I don't know how to properly attach the gesture to the ModelEntity. Any help is great. Thank you
import SwiftUI
import RealityKit
import RealityKitContent
import Foundation
@main
struct testApp: App {
@State var immersionStyle:ImmersionStyle = .mixed
var body: some Scene {
ImmersiveSpace {
ContentView()
}
.immersionStyle(selection: $immersionStyle, in: .mixed, .full, .progressive)
}
}
struct ContentView: View {
@State private var lastPosition: SIMD3<Float>? = nil
@State var subscription: EventSubscription?
@State private var isDragging: Bool = false
var sphere: ModelEntity {
let mesh = MeshResource.generateSphere(radius: 0.05)
let material = SimpleMaterial(color: .blue, isMetallic: false)
let entity = ModelEntity(mesh: mesh, materials: [material])
entity.generateCollisionShapes(recursive: true)
return entity
}
var drag: some Gesture {
DragGesture()
.targetedToEntity(sphere)
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
var body: some View {
Text("Hello, World!")
RealityView { content in
//1. Anchor Entity
let anchor = AnchorEntity(world: SIMD3<Float>(0, 0, -1))
let ball = sphere
//1.2 add component to ball
ball.components.set(InputTargetComponent())
//2. add anchor to sphere
anchor.addChild(ball)
content.add(anchor)
subscription = content.subscribe(to: SceneEvents.Update.self) { event in
let currentPosition = ball.position(relativeTo: nil)
if let last = lastPosition, last != currentPosition {
print("Sphere moved from \(last) to \(currentPosition)")
}
lastPosition = currentPosition
}
}
.gesture(drag)
}
}